Reputation: 171
public int sumOfDigits(int num){
return num == 0 ? 0 : num % 10 + sumOfDigits(num/10);
}
Upvotes: 0
Views: 122
Reputation: 111
That's a Java ternary operator, but in most cases it is not used since if-else statements are much more readable, which can also do the same function ternary operators can do. But if you would like to make shorter code lines, then this is preferred.
Upvotes: 0
Reputation: 56
This method calculates sum of the numbers representing base 10 integer numbers. The method is called recursively with % operator to separate digits in the number and then add them to form the result.
Eg - 234 into 2 + 3 + 4 = 9
However, if you pass a integer in base other than base 10, the method still gives the result for base 10
Eg sumOfDigits(0b1011010)
-> answer is 9 for 90 in base 10
sumOfDigits(0x532)
-> answer is 7 for 1330 in base 10
Following is the change for binary and octal values to get the sum of the representing numbers
return num == 0 ? 0 : num % 2 + sumOfDigits(num / 2);
return num == 0 ? 0 : num % 8 + sumOfDigits(num / 8);
Upvotes: 0
Reputation: 15445
That is the Java ternary operator. It is similar to ternary operators in other languages. In this case:
return <boolean expression> ? <if true> : <if false>;
You have posted a recursive algorithm to calculate the sum of digits in an integer.
Two equivalent methods are posted below:
public int sumOfDigitsIf(int num) {
if (num == 0) {
return 0;
} else {
return num % 10 + sumOfDigitsIf(num / 10);
}
}
public int sumOfDigitsLoop(int num) { // useful to examine if you aren't used to recursive algorithms
int value = 0;
while (num > 0) {
value += num % 10;
num /= 10;
}
return value;
}
Upvotes: 1
Reputation: 5868
return num == 0 ? 0 : num % 10 + sumOfDigits(num/10);
Is equivalent to:
if(num==0)
{
return 0;
}
else
{
return num % 10 + sumOfDigits(num/10); // this is recursive call. It gets called until num is reduce to 0
}
This basically calulates as following:
If num=768
result= 7+6+8
.
Upvotes: 1
Reputation: 689
This function calculates the sum of the digits of the number recursively. First, if the number is 0, it returns 0, as the sum of the digits of 0 is 0. Then, it calculates the digit in the 1s place with num % 10, and adds that to the sum of the digits of the remaining places, num / 10 is the remaining places, and it calls sumOfDigits() on that number.
Upvotes: 0
Reputation: 13854
sumOfDigits is a method which accepts int argument and the return type is also int.
If 0 is passed then it will return 0 other wise it will return num % 10 + sumOfDigits(num/10)
If a number other than 0 is passed this will continue as long as entered number becomes 0
Upvotes: 1
Reputation: 312259
This is a recursive calculation of the sum of digits - as long as you haven't consumed all the digits, it adds the last one with the sum of all the previous ones.
Upvotes: 3