LintCode第147题(水仙花数)

  • 题目:

水仙花数的定义是,这个数等于他每一位数上的幂次之和 见维基百科的定义

比如一个3位的十进制整数153就是一个水仙花数。因为 153 = 13 + 53 + 33。

而一个4位的十进制数1634也是一个水仙花数,因为 1634 = 14 + 64 + 34 + 44。

给出n,找到所有的n位十进制水仙花数。

  • 首先了解一下math.pow()函数

pow() 函数用来求 x 的 y 次幂次方,其原型为:double pow(double x, double y);设返回值为 ret,则 ret = xy。

  • 题目解答

package lintcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Solution_147 {
	 public List<Integer> getNarcissisticNumbers(int n) {
	        int limit_latter = (int)Math.pow(10, n);//10^n
	        int limit_former = (int)Math.pow(10, n - 1);//10^(n-1)
	        int[] digit = new int[n];
	        int count;
	        int dup1 , dup2;
	        List<Integer> result = new ArrayList<>();
            if(n == 1)
                limit_former = 0;//添加0的情况
	        int num = limit_former;
	        for (; num < limit_latter; num++) //limit_former开始
	        {
	            dup1 = num;
	            dup2 = num;
	            count = 1;
	            //个位:digit[0];十位:digit[1];百位:digit[2];千位:digit[3];...
	            while(count<n+1) //1->n
	            {
	                digit[count-1] = dup1 % 10;// 求各个位,并保存在digit[](0->n-1)中
	                dup1 /= 10;
	                count++;
	            }
	            for (int m = 0; m < n; m++) 
	            {
	                dup2 -= Math.pow(digit[m], n);//(digit[m])^n;判断水仙花数(减到0为止)
	            }
	            if (dup2 == 0)
	            {
	                result.add(num);
	            }
	        }
	        return result;
	    }
     public static void main(String[] args) {
		 Solution_147 solution = new Solution_147();
		 Scanner s=new Scanner(System.in);
		 int n;
		 n=s.nextInt();
		 System.out.println(solution.getNarcissisticNumbers(n));
	 }
}

结果:

参考链接:https://blog.csdn.net/sjpz0124/article/details/45191299https://www.jianshu.com/p/0591b8592c23

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值