Problem:
Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
sumDigits(126) → 9
sumDigits(49) → 13
sumDigits(12) → 3
Solution:
public int sumDigits(int n) { if (n < 10) return n; return (n % 10) + sumDigits(n/10); }
public int sumDigits(int n) {
ReplyDeleteif (n <= 0) return n;
return (n % 10) + sumDigits(n/10);
}
doesnt work
ReplyDeletenever mind
ReplyDeletepublic int sumDigits(int n) {
ReplyDeleteif(n == 0) {
return 0;
}
return n % 10 + sumDigits(n / 10);
}
public int sumDigits(int n) {
ReplyDeleteif (n < 10) return n;
return (n % 10) + sumDigits(n/10);
}
//write a recursive function that calculate the sum of the digits
ReplyDeletepublic int sumDigits(int n) {
if(n<0)throw new IllegalArgumentException("enter a positive number");
if(n==0)return 0;
int rightmost = n%10, leftmost = n/10;
return rightmost +sumDigits(leftmost);
}