avihu24
avihu24

Reputation: 55

How to deal with a summing digits method

I built 2 methods 1 get a number's digits, the 2nd sums all the digits of the number. It works , but for some reason when i type the number 11111 or higher it returns a wrong result.

For ex. the number 11111 returns 3 instead of 5

public class test_2 {
    public static int getDigits(int x) {
        int counter = 0;
        while (x > 0) {
            x /= 10;
            counter++;
        }

        return counter;
    }

    public static int getNumber(int y) {
        int New = 0;
        for (int i = 0; i <= test_2.getDigits(y); i++) {
            New += (y % 10);
            y /= 10;

            if (y < 10 && y > 0)
                New += (y % 10);
        }

        return New;
    }
}

Upvotes: 2

Views: 59

Answers (1)

Eran
Eran

Reputation: 394116

There are multiple issues with your code, Follow below

  1. test_2.getDigits(y) changes in each iteration of the loop, since y keeps changing

  2. if (y < 10 && y > 0) condition is not necessary

The following will work:

public static int getNumber(int y) {
    int New = 0;
    for (int i = 0, len = getDigits(y); i < len; i++) {
        New += (y % 10);
        y /= 10;
    }

    return New;
}

Or simply:

public static int getNumber(int y) {
    int New = 0;
    while (y > 0) {
        New += (y % 10);
        y /= 10;
    }

    return New;
}

Upvotes: 4

Related Questions