简体   繁体   中英

Sum of squares of digits of an integer in Java

I am trying to write a recursive implementation of a method that takes a non-negative argument, and returns the sum of the squares of its digits. For example, sumSquareDigits(10) should return 1 and sumSquareDigits(103) should return 10.

This is my code :

public static int sumSquareDigits(int n) {
    if (n < 10) return n^2;
    return (((n % 10)^2) + sumSquareDigits(n/10));
    }

For example for an given integer 625, it would be something like:

(625 % 10)^2 + (62,5 % 10)^2 + (6,25)^2 = 5^2 + 2^2 + (6,25)^2

which of course is wrong because the last term should be 6 and not 6,25. What I am looking for is a way to truncate 6,25 so that it becomes 6.

How do we do this? And I'd appreciate any hints to implement this function better (I'm new in Java).

Thanks!

In Java, ^ is not "to the power" of, it is the bitwise XOR operator. To perform powers in Java use Math.pow . Bear in mind that Math.pow returns a double so you will need to cast it to an int if you only want a whole number. Eg

if (n < 10) return (int)Math.pow(n, 2);

Of course, as msandiford pointed out, if you only need to calculate powers of 2, it is probably easier to just multiply a number by itself. Eg

if (n < 10) return n * n;

The ^ is for the bitwise XOR operator. You could use Math.pow , and cast the results to int since Math.pow returns a double :

public static int sumSquareDigits(int n) {
    if (n < 10) return (int) Math.pow(n, 2);
    return (int)((Math.pow((n % 10), 2)) + sumSquareDigits(n/10));
}

Or since it's only squared, just multiply the base by itself:

public static int sumSquareDigits(int n) {
    if (n < 10) return n * n;
    return ((n % 10) * (n % 10)) + sumSquareDigits(n/10);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM