黑马程序员技术交流社区

标题: 水仙花新算法 [打印本页]

作者: 何伟    时间: 2013-2-26 14:20
标题: 水仙花新算法

class HomeWork2 {
        private static int Sum;
        private static int temp;
        private static int digit = 3; // 100-999各个位数3次幂相加结果,1000-9999各个位数4次幂相加结果,以此类推

        public static void main(String[] args) {
                for (int num = 99; num < 1000; num++) {
                        temp = num;
                        while (temp != 0) {
                                Sum += (int) Math.pow(temp % 10, digit);
                                temp /= 10;
                        }
                        if (num == Sum) {
                                System.out.println(Sum);
                        }
                        Sum = 0;
                }
        }
}

研究研究

作者: 颜春    时间: 2013-2-27 17:26
这样试试:交流交流  
int n;
              for (n=150; n < 160; n++)
            {
                int a = n % 10; //个位数字
                int i = n / 10;
                int b = i % 10; //十位数字
                i = i / 10;
                int c = i % 10; //百位数字



                if ((Math.Pow(a, 3) + Math.Pow(b, 3) + Math.Pow(c, 3)) == n)
                {
                    Console.WriteLine("{0}是水仙花数", n);
                }
                else
                {
                    Console.WriteLine("{0}不是水仙花数", n);
                }
              }
           
            Console.ReadLine();


作者: 杨建聪    时间: 2013-2-27 22:28
用三级for循环控制 百十个位就可以了

这是我昨天刚做的,给大家参考下

/*
        2.水仙花  100-999中有多少个像
       153的数字 ?      1*1*1+5*5*5+3*3*3=153

        */
    public static int getCount()
        {   
                int count=0;
                for (int x=1;x<=9 ;x++ )
                {
                        for (int y=0;y<=9 ;y++ )
                        {
                                for (int z=0;z<=9 ;z++ )
                                {
                                        int sum=100*x+10*y+z;
                                        if(x*x*x+y*y*y+z*z*z==sum)
                                        {
                                                count++;
                                                System.out.println(sum);
                                        }
                                               

                                }
                        }
                }
                return count;
    }
作者: 何伟    时间: 2013-2-27 22:32
杨建聪 发表于 2013-2-27 22:28
用三级for循环控制 百十个位就可以了

这是我昨天刚做的,给大家参考下

普遍好像就是这个做法,帖子的做法  是我们班长自己想的
作者: 黄玉昆    时间: 2013-3-4 16:09
是不是能用递归做呢?你可以尝试一下。
作者: 何伟    时间: 2013-3-4 16:16
黄玉昆 发表于 2013-3-4 16:09
是不是能用递归做呢?你可以尝试一下。

这个还在不知道,有时间研究研究
作者: 黄玉昆    时间: 2013-3-4 16:21
何伟 发表于 2013-3-4 16:16
这个还在不知道,有时间研究研究

嗯,好好研究,就是对自己技术的提高,思想很重要的。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2