50道编程题之03:打印出所有的水仙花

package com.demo;

import java.util.ArrayList;

/**
 * Created by 莫文龙 on 2018/3/26.
 */
public class Demo2 {

    /**
     *
     * 打印所有的水仙花,所谓的水仙花是指一个三位数,其各位数字立方和等于该数本身
     *
     */

    public static void main(String[] args) {
        int start = 100;
        int end = 999;
        int count = 0;
        ArrayList list = new ArrayList<>();
        for (int i = start ; i <= end ; i ++) {
            int a = i / 100;
            int b = (i - a * 100) / 10;
            int c = (i - a * 100 - b * 10) / 1;
            int sum = (int)(Math.pow(a,3) + Math.pow(b,3) + Math.pow(c,3));
            if (sum == i ) {
                count ++;
                list.add(i);
            }
        }
        System.out.println("水仙花的个数为:" + count);
        for (Integer i : list) {
            System.out.print(i + ",");
        }
    }
}

你可能感兴趣的:(50道Java基础编程练习题)