Thursday, June 7, 2007

Q8: sum calculation

Q: calculate the sum of s in s = a + aa + a...a. a is a number. The last number is a a digits number. For example, a is 5, then the formula is s = 5 + 55 + 555 + 5555 + 55555.

A:

public class Sum {
private static int getNumber(int a, int len){
int num =0;
for(int i=1; i<=len; i++){
num = num * 10 + a;
}
System.out.println("num " + len +": " + num);
return num;
}

public static int getSum(int a){
int sum =0;
for(int i=1; i<=a; i++){
sum += getNumber(a, i);
}
return sum;
}
public static void main(String[] args) {
System.out.println("Sum for 5: " + Sum.getSum(5));
}
}

result:
num 1: 5
num 2: 55
num 3: 555
num 4: 5555
num 5: 55555
Sum for 5: 61725

No comments: