Nevada Nevada - 5 months ago 10
Java Question

How to find sum of first three digits

I'm new in Java and I try to find the sum of first three digits in

int
number.
I have a number
123456
I want to find the sum of first three digits
123
and then find sum of last three digits
456
and then compare it. I can't understand how to do this. I code next:

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int length = (int) Math.ceil(Math.log10(number));

for (int i = 1; i <= 3; i++) {
System.out.println(i);
}

System.out.println(length);
System.out.println(number);
}


I think that I shoud to use for loop, but I'm not sure. I know how to count the length of a number. But how to how to find the sum of the first three numbers and last three?

Answer

Here's a straightforward way of doing it, making the assumption that your integer has an even number of digits...

public class Test {
    public static void main(String[] args) {
        // Makes the assumption that the input integer contains an even number of digits.
        int x = 123456;
        String s = Integer.toString(x);
        int[] count = new int[2];
        for (int i = 0; i < s.length(); i++) {
            int digit = Integer.parseInt(s.substring(i, i + 1));
            int countIndex = (int)Math.floor(i * 2 / s.length());
            count[countIndex] += digit;
        }

        int half = s.length() / 2;
        System.out.println("First Sum of " + s.substring(0, half) + ": " + count[0]);
        System.out.println("Second Sum of " + s.substring(half) + ": " + count[1]);
    }
}

Alternate Method

Here's another way of doing it without using the arrays above, and actually simplified the logic by abstracting the sum to a method.

public class Test {
    public static void main(String[] args) {
        // Makes the assumption that the input integer contains an even number of digits.
        int x = 123456;
        String s = Integer.toString(x);
        int half = s.length() / 2;
        String firstHalf = s.substring(0, half);
        String secondHalf = s.substring(half);
        System.out.println(firstHalf);
        System.out.println(secondHalf);
        int sum1 = sumString(firstHalf);
        int sum2 = sumString(secondHalf);
        System.out.println("Sum 1: " + sum1);
        System.out.println("Sum 2: " + sum2);
    }

    private static int sumString(String s) {
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            sum += Integer.parseInt(s.substring(i, i + 1));
        }

        return sum;
    }
}
Comments