[算法] java之 水仙花数

package com.pardon.test;

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * 水仙花数 153 = 1^3+5^3+3^3 要求:输出所有在m和n范围内的水仙花数
 * 
 * 100<=m<=n<=999
 * 
 * @author pardon110
 * 
 * 注意:java是存在块级作用域 的
 *
 */
public class TestFllower {

    public static void main(String[] args) {

        System.out.println("请输入水仙花数的范围m,n [100<=m<=n<=999]");
        Scanner scan = new Scanner(System.in);

        int step = 0;
        int m = 0, n = 0;
        while (scan.hasNext()) {
            String in = scan.next().toString();

            if (step == 0) {
                m = Integer.parseInt(in);
                System.out.println("您输入的起始数据是" + in);
            }

            if (step == 1) {
                n = Integer.parseInt(in);
                System.out.println("您输入的终止数据是" + in + "\n请输入s开始计算");
            }

            if (step == 2 && in.equals("s")) {
                System.out.println("计算水仙花数据完毕...");
                follower(m, n);
                step =0;
                break;
            }

            step++;
        }

        scan.close();
    }

    public static void follower(Integer m, Integer n) {

        int k=0;
        List<Integer> list = new LinkedList<Integer>();

        for (int a,b,c,i = m; i <= n; i++) {
            a = i / 100;        //百位
            b = i / 10 % 10;    //十位
            c = i %10;          //个位

             if(a*a*a+b*b*b+c*c*c == i) {
                 list.add(i);
                 k++;
             }
        }
        if(k == 0) {
            System.out.println("no");
        }else {
            System.out.println("该范围内存在"+k+"个水仙花敉,分别是\n"+list);
        }
    }

}

console

请输入水仙花数的范围m,n [100<=m<=n<=999]
100
您输入的起始数据是100
900
您输入的终止数据是900
请输入s开始计算
s
计算水仙花数据完毕...
该范围内存在4个水仙花敉,分别是
[153, 370, 371, 407]

猜你喜欢

转载自blog.csdn.net/u011584949/article/details/82737213