求N位数的水仙花数--恒生笔试题

求N位数的水仙花数--恒生电子编程笔试题

/**
 * 输出水仙花数。
 * 从键盘输入一个正整数,倒序输出所有的 大于10 且 小于该数 的水仙花数。
 * 水仙花数是 指一个n位正整数,它的各位数字的n次幂之和等于他本身。
 * 试编写相应程序。
 * 例如:153 = 1^3 + 5^3 + 3^3
 *      1634 = 1^4 + 6^4 + 3^4 + 4^4
 */
import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        // 从键盘读入一个数字
        int num = scanner.nextInt();

        for (int i = num; i > 10; i--) {
    
    
            // res:获取这个数字的有多少位
            int j = i, res = 0, n = i, sum = 0;
            while (j != 0) {
    
    
                res++; // 标志位+1,得到了从键盘输入数字的位数
                j /= 10; // 循环除以10
            }
            while (n != 0) {
    
    
                sum += Math.pow(n % 10, res); // Math.pow()计算出每个位数上的数字的res次方,做循环累加
                n /= 10;
            }
            if (sum == i) {
    
     // 和数等于当前的输入,就打印出来
                System.out.println(i);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44807756/article/details/129909071