枚举算法(Enumeration algorithm)实例一

时间:2022-05-03
本文章向大家介绍枚举算法(Enumeration algorithm)实例一,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

(建议电脑看原文链接,平台的排版不太好,太累了。)描述:在n位的整数中,例如153可以满足1^3 + 5^3 + 3^3 = 153,这样的数称之为Armstrong数。

将所有的Armstrong数按小到大排序,试写出一程序找出n位数以下的所有Armstrong数,网上大多数是已知位数求确定位数下的Armstrong数,本题在此基础上提高了一定的难度。

手机浏览图片,电脑用户浏览下面的代码

/**
 * @Author: zhaoyaojing
 * @Email: null
 * @Date: 02/02/2018
 * @Time: 8:53 PM
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ArmstrongNum {
    public ArmstrongNum(){
    }

    /**
     * 枚举法
     * 求n位数以下的所有Armstrong数,也就是10的(n+1)次幂以下的数
     */
    public void getAllArmstrongNum1(int n){

        //从1开始到10的n次幂
        for(int i = 1; i < (int) Math.pow(10, n); i++){

            //sum表示一个i位数等于其个位数的i次方之和,i小于等于n。
            int sum = 0;

            //把每个数查分成i个个位数,放在数组里
            int[] mun = new int[n];

            //获得当下查询值
            int thisNum = i;

            //j为当下查询值的位数
            int j = 0;

            //得到一个存放当下数每位上的数的数组mun
            while (thisNum > 0){
                mun[j] = thisNum % 10;
                thisNum = thisNum / 10;
                ++j;
            }

            //求得sum
            for(int k = 0; k < n; k++){
                sum = sum + (int)Math.pow(mun[k], j);
            }

            //如果i属于Armstrong数,则输出,以一个空格为间隙。
            if(i == sum){
                System.out.print(i + " ");
            }
        }
    }

    public static void main(String[] args) throws Exception, IOException {
        // TODO Auto-generated method stub
        ArmstrongNum armstrongNum = new ArmstrongNum();
        System.out.print("求n位数以下的Armstrong数,请先输入n的值:n");

        //输入n
        int n = Integer.parseInt(new BufferedReader
                (new InputStreamReader(System.in)).readLine());

        //得到n位数以下的所有Armstrong数
        armstrongNum.getAllArmstrongNum1(n);
    }
}
求n位数以下的Armstrong数,请先输入n的值:
5
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084