lintcode算法题之147-水仙花数

22 篇文章 0 订阅

47. 水仙花数

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

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

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

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

样例

样例 1:

输入: 1
输出: [0,1,2,3,4,5,6,7,8,9]

样例 2:

输入:  2
输出: []	
样例解释: 没有2位数的水仙花数。

 

代码区:

public class Solution {
    /**

     * username:softstarhhy
     * @param n: The number of digits
     * @return: All narcissistic numbers with n digits
     */
    public List<Integer> getNarcissisticNumbers(int n) {
        
        // write your code here
        List list=new ArrayList<Integer>();
       int start = (int)Math.pow(10, n-1);
        int end = (int)Math.pow(10, n);
       /* for(int s=0;s<n;s++)
        {
            n=(int)Math.pow(10,s+1);
            if(s==(n-1))
            {
                n=n-1;
            }
        }*/
        if(start == 1)
            start = 0;

        for(int j=start;j<=end;j++)
        {
        
        String sxhstr=String.valueOf(j);
        char[] charsxh=sxhstr.toCharArray();
        int[] numbers=new int[charsxh.length];
        for(int k=0;k<numbers.length;k++)
        {
            numbers[k]=charsxh[k]-'0';
            
        }
        int len=numbers.length;
        int current=0;
        int sum=0;
        for(int i=0;i<len;i++)
        {
            current=(int)Math.pow(numbers[i],len);
            sum=sum+current;
            
            if((j==sum)&&(i==(len-1)))
            {
                list.add(j);
               
            }
            
        
        }
        
       }
       return list;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值