Sardor Vaqqosov
Sardor Vaqqosov

Reputation: 25

sum digits a number in Java

I have a bunch of numbers.Each digit of those numbers is concatenated n times and then summed. I have to write function which is returns 1 if sum equals number else returns 0.

public static int checkConcatenatedSum(int n, int catlen) {
        char[] charArray = String.valueOf(n).toCharArray();
        int[] test = new int[charArray.length];
        String[] digit = new String[charArray.length];
        int sum = 0;
        for (int j = 0; j < charArray.length; j++){
            for(int i = 0; i < catlen; i++){
                digit[j] += charArray[j];
            }
            test[j] = Integer.parseInt(digit[j]);
            sum += test[j];
        }
        if(sum == n){
            return 1;
        }
        else return 1;
    }

digit[j] begins with null every time.

Upvotes: 1

Views: 892

Answers (4)

cl-r
cl-r

Reputation: 1264

Another way is to test if array[?] is 'null' avoiding to create a temporary object String for Garbage Collector

for (int j = 0; j < charArray.length; j++){
    for(int i = 0; i < catlen; i++){
       digit[i] = digit[i] == null ? charArray[j] :  digit[i] + charArray[j];
    }
    test[j] = Integer.parseInt(digit[j]);
    sum += test[j];
}

EDIT Your second return is erroneous (0 attempted);

Upvotes: 0

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26048

for (int j = 0; j < charArray.length; j++){
    digit[j] = new String();
    for(int i = 0; i < catlen; i++){
        digit[j] += charArray[j];
    }
    test[j] = Integer.parseInt(digit[j]);
    sum += test[j];
}

Other answers are right, but just a quick addition to your existing loop that achieves it without making a new loop.

Upvotes: 1

Attila
Attila

Reputation: 28762

When you create an array (of String in this case), its elements are null at first.

You need to initialize the elements:

String[] digit = new String[charArray.length];
for (int i = 0; i < digit.length) {
  digit[i] = new String();
}

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

When you initialize a new array of objects (String[] strs = ...) all elements in the array will be initialized to null, but you can then iterate over the array and set them all to some value (like "")

Upvotes: 1

Related Questions