简体   繁体   中英

How am I supposed to loop repeatedly over a "function" in Java?

I have written a code which takes in a number and multiplies it's digits together and here it is.

public class Happy
    {   public static int findSum(int k)
        {
            int sum = 0;
            while (k != 0)
            {
                sum = sum + ((k % 10)*(k % 10));
                k = k/10;
            }
            return sum;
        }
        public static void main(String args[])
        {
            System.out.println(findSum(713));
        }
    }

and my code returns 19 when my input is 82, because 1^2 + 9^2 is 82.

However, I want to modify my code so that my code would continue to square each digit and add them together until there is only one non-zero digit left .

So basically, if my input is 19, the code would return 1 because:

1^2 + 9^2 = 82, from which digits 8 and 2 would do: 8^2 + 2^2 = 68, from which digits 6^2 + 8^2 = 100, from which 1^2 + 0^2 + 0^2 = 1.

What changes to my code should I make in order for it to work?

You could call your method recursivly by checking if sum > 9

public static int findSum(int k)
{
    int sum = 0;
    while (k != 0)
    {
        sum = sum + ((k % 10)*(k % 10));
        k = k/10;
    }
    return sum > 9 ? findSum(sum) : sum;
}
    public static boolean check_base10(int k){
            String total = String.valueOf(k);
            for (int i = 1; i < total.length(); i++) {
                if (total.charAt(i) != '0' ) {
                    return false;
                }
            }
            return true;
        }
    public static void main(String args[])
        {
            int result = findSum(713) ;
            do { /* rerun the function until the condition of while is verified*/
                result = findSum(result) ;
               
            }
            while(!check_base10(result)) ; /* check wether number is base 10 */
            System.out.println(result);
        }

I think this should answer your question, you rerun your function until your condition is successfully met in the while()

Only start accumulating after encountering the first non-zero remainder:

public static int findSum(int k) {
    int sum = 0;
    boolean foundNonZero = false:
    for (; k != 0; k /= 10) {
        if (foundNonZero) {
            sum += (k % 10)*(k % 10);
        } else {
            foundNonZero = k % 10 != 0;
        }
    }
    return sum;
}

Note the brevity achieved by the replacement of while with for and use of terse arithmetic syntax.

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