2

Is there a more elegant way to write this recursively? Armstrong Numbers

PS: been out of school for 15 years this is not homework, just some code I am trying to convert from iterative to recursively.

import java.util.Scanner;

public class RecArmstrong {
public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = keyboard.nextInt();

    //Error checking
    while(number < 0 || number > 100000){
        System.out.print("Enter a number: ");
        number = keyboard.nextInt();
    }

    if(arm(number) == number)
        System.out.println(number + " is an armstrong number");
    else
        System.out.println(number + " is not an armstrong number.");

}

public static long arm(long n){

    long temp, sum, digits = 0;
    long remainder;
    temp = n;
    sum = 0;

    if (temp == 0)
        return 0; //base case
    else{
        while (temp != 0){
        digits++; //number of digits for exponent
        temp = temp / 10;
    }
    temp = n; //set temp back to original number
    while (temp != 0){
        remainder = temp % 10;
        sum += Math.pow(remainder, digits);
        temp = temp / 10;
    }
        return sum + arm(temp);
    }
}
}
4

2 回答 2

4

也许我弄错了(这里是凌晨 1 点..),但据我所知,您的实现实际上根本不是递归。和

while (temp != 0){
        remainder = temp % 10;
        sum += Math.pow(remainder, digits);
        temp = temp / 10;
    }

您迭代地进行整个计算,直到 tmp 为 0。因此在下一行

返回总和 + 臂(温度);

arm(temp) 将始终返回 0!

我拼凑了一个我自己的快速递归,它从最后一个开始逐位工作。函数重载是必要的,因为每个递归调用都需要原始数字的总长度。

public static long arm(long n){
   return arm(n, Integer.toString(n).length());
}
public static long arm(long n, int num_digits){

   if(n==0) //recursion finished
      return;
   // n%10 gives last digit
   return java.lang.Math.pow(n%10,num_digits) + arm(n/10, num_digits);
}   

我希望你喜欢它 ;-)

于 2012-07-28T23:28:03.397 回答
0

如果你想使用 java 流来做,你可以这样做。

public boolean isArmstrongNumber(String number) {
    int exponent = number.length();
    if (Integer.parseInt(number) == number.chars()
            .map(n -> n - '0')
            .map(n ->(int) Math.pow(Integer.parseInt("" + n),exponent))
            .sum())
        return true;
    else return false;
}
于 2018-05-23T15:06:04.487 回答