基本算法思维——求指定区间的水仙花数

问题

求100-999区间的水仙花数

水仙花数性质:一个三位数,它的每个位上的数字的 3次幂之和等于它本身。

分析

(1)确定位数为3

(2)整数%10获得个位值,整数/10去掉个位值。

code

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
    public static void main(String args[]) {
        
        Scanner s = new Scanner(System.in);
        int m,n;
        while(s.hasNext()) {
            m = s.nextInt();
            n  =s.nextInt();
            Integer[] arr;
            if(((arr=function(m,n))==null)) {
                System.out.println("no");
            }else {
                for(int i=0;i<arr.length;i++) {
                    System.out.print(arr[i]+" ");
                }
            }
        }
    }
    //查询此区间是否存在水仙花数,并进行记录
    public static Integer[] function(int m, int n) {
        List<Integer> arr = new ArrayList<>();  //使用动态数组记录水仙花数
        for(int i=m;i<=n;i++) {
            int temp = i;
            int sum = 0;
            while(temp>0) {
                sum+=Math.pow(temp%10, 3);//获得个位的3次方
                temp = temp/10;//去掉个位
            }
            /*
             * 判断是否满足水仙花数性质
             */
            if(sum==i) { 
                arr.add(i);
            }
        }
        //如果记录不为空,返回基本类型的数组
        if(arr.size()!=0) {
            Integer[] a = new Integer[0];
            a = arr.toArray(a);
            return a;
        }
        return null;
    }
    
    
    

}

猜你喜欢

转载自www.cnblogs.com/dream-flying/p/12794912.html
今日推荐