Skip to main content

Program in Java: Digital River

 A digital river is a sequence of numbers where every number is followed by the same number plus the sum of its digits. In such a sequence 123 is followed by 129 (since 1 + 2 + 3 = 6), which again is followed by 141.
We call a digital river river K, if it starts with the value K.
For example, river 7 is the sequence beginning with {7, 14, 19, 29, 40, 44, 52, ... } and river 471 is the sequence beginning with {471, 483, 498, 519, ... }.
Digital rivers can meet. This happens when two digital rivers share the same values. River 32 meets river 47 at 47, while river 471 meets river 480 at 519.
Given two meeting digital rivers print out the meeting point.


public class DigitalRiver {
    public static int findMeetingPoint(int river1, int river2) {
        int current1 = river1;
        int current2 = river2;

        while (current1 != current2) {
            if (current1 < current2) {
                current1 = nextNumber(current1);
            } else {
                current2 = nextNumber(current2);
            }
        }

        return current1; // or current2, both are equal at this point
    }

    private static int nextNumber(int num) {
        int sumOfDigits = sumDigits(num);
        return num + sumOfDigits;
    }

    private static int sumDigits(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        int river1 = 32;
        int river2 = 47;
        int meetingPoint = findMeetingPoint(river1, river2);
        System.out.println("Meeting point of rivers " + river1 + " and " + river2 + " is: " + meetingPoint);
    }
}

Popular posts from this blog