简体   繁体   中英

How do I use a recursion for sum of squares from user input?

Let's say for the user input 1 , I can easily find the square of it. (A single digit input) How do I use a recursive method to find the sum of squares (input with more than one number) eg 12345 should give 1*1 + 2*2 + 3*3 + 4*4 + 5*5 = 55 ? For the base case, it is correct to as num == 1 right? And from there, how do I compute the subsequent number behind 1 ?

public static int squareSum(int num) {
    if (num == 1) {
        return num*num;
    } else {
        return 0; 
    }
}

You have to think about the small steps first. It is all about extracting the digits and the calculating the squares.

public static int squareSum(int num) {
    if (num == 0) return 0;
    return (num%10)*(num%10) + squareSum(num/10); 
}

For 12345 :-

f(12345) 

f(1234)+5*5

f(123)+4*4+5*5

f(12)+3*3+4*4+5*5

f(1)+2*2+3*3+4*4+5*5

f(0)+1*1+2*2+3*3+4*4+5*5

The problem is, that you can't get the number at position x easily. The fact that 12345 consists of the numbers 1 , 2 , ... is only obvious in the decimal system. We will therefore store our number as a String , take each character and parse it to an integer. Then we square the number and add them

int i sum = 0;
String iAsString = i;
for (int i = 0; i < iAsString.length; i++) {
    int currentNumber = Character.getNumericValue(iAsString.charAt(i));
    sum += currentNumber * currentNumber;
}

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