Home > Software design >  Issue while compare and sum digits of two numbers
Issue while compare and sum digits of two numbers

Time:06-07

So, the thing is that I have two lines with two numbers on each line. On each line the numbers are separated by space. What I'm trying to do is to compare which number is bigger on the line and sum digits of the bigger number.

Example

1000 2000
2000 1000

In this case the output should be

2
2

because on the first line the right numbers is bigger and the sum of it digits is 2. The second line is the opposite.

What I have so far is this

    int sum = 0;

    for (int i = 0; i <= 2; i  ) {
        String numbers = scanner.nextLine();

        String[] parts = numbers.split(" ");
        double leftNumber = Double.parseDouble(parts[0]);
        double rightNumber = Double.parseDouble(parts[1]);

        if ( leftNumber > rightNumber ) {
            while (leftNumber > 0) {
                sum = (int) (sum   leftNumber % 10);
                leftNumber = leftNumber / 10;
            }
        } else {
            while (rightNumber > 0) {
                sum = (int) (sum   rightNumber % 10);
                rightNumber = rightNumber / 10;
            }
        }
        System.out.println(sum);
    }

Result that I've get is

2
4

it is adding the second line result to the first one. How can I avoid this?

CodePudding user response:

Why not make things easier on yourself and just treat the integers as strings for the purpose of summing the digits?

    while (scanner.hasNext()) {
        int larger = Math.max(scanner.nextInt(), scanner.nextInt());
        String sLarger = String.valueOf(larger);
        int digitsSum = 0;
        for (int i = 0; i < sLarger.length(); i  ) {
            digitsSum  = sLarger.charAt(i) - '0';
        }
        System.out.printf("Larger number %s sums to %d%n", sLarger, digitsSum);
    }
  •  Tags:  
  • java
  • Related