My first try that worked:
int S(int x){
int sum=0, y=0;
while (x!=0){
if (x < 10) {
y = x;
} else {
y = x % 10;
}
x = (x - y) / 10;
sum += y * y;
}
return sum;
}
Returns:
DigitsSum(55)=50 [5*5 + 5*5]
DigitsSum(230)=13 [2*2 + 3*3 + 0*0]
DigitsSum(37)=58 [3*3 + 7*7]
U P D A T E
A better solution:
int ur_num;
int sum_of_sq=0;
while(ur_num!=0){
remainder=ur_num%10;
sum_of_sq += remainder*remainder;
ur_num = ur_num/10;}
No comments:
Post a Comment