zoukankan      html  css  js  c++  java
  • 基本算法思维——求指定区间的水仙花数

    问题

    求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;
        }
        
        
        
    
    }
  • 相关阅读:
    C语言入门(16)——C语言的数组
    快速插入一百万行数据储存过程
    如何将两个表名对调
    MySQL规范
    MySQL运行环境部署规范
    mysql查看存储过程
    批量杀死MySQL连接的几种方法
    查看堵塞的SQL
    mysqldump备份脚本
    查看当前的数据和索引的总大小
  • 原文地址:https://www.cnblogs.com/dream-flying/p/12794912.html
Copyright © 2011-2022 走看看