判断一个数是否时水仙花数
水仙花数定义:每位数的三次方相加之和为这个数本身
方法一:计算每个位数
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import java.util.*; public class Main { final static int max0=10000; public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n =sc.nextInt(); //分别得到每位数 int a =n/100; int b=n%100/10; int c=n%10; if(a*a*a+b*b*b+c*c*c==n) { System.out.print("YES"); } else System.out.print("NO"); } }
方法二:读入整数截取字符串的形式
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import java.util.Scanner; public class Main { final static int max0=10000; public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n =sc.nextInt(); //分别得到每位数 char[] c= Integer.toString(n).toCharArray(); int a=(c[0]-48)*(c[0]-48)*(c[0]-48); int b=(c[1]-48)*(c[1]-48)*(c[1]-48); int c1=(c[2]-48)*(c[2]-48)*(c[2]-48); if(a+b+c1==n) { System.out.print("YES"); } else System.out.print("NO"); } }
输出某个区间内的水仙花数
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35import java.util.*; public class Main { final static int max0=10000; public static void main(String[] args) { Scanner sc= new Scanner(System.in); int min=sc.nextInt(); int max=sc.nextInt(); int sum=0; int[] num =new int[max0]; for(int n=min;n<=max;n++) { int a =n/100; int b=n%100/10; int c=n%10; if(a*a*a+b*b*b+c*c*c==n) { num[sum++]=n; } } if(sum==0) System.out.print("NO"); else { for(int i=0;i<sum;i++) { System.out.print(num[i]); if(i<sum-1) System.out.print(" "); } } } } /** 借助于数组的方法 */
最后
以上就是敏感乌龟最近收集整理的关于算法-水仙花数的全部内容,更多相关算法-水仙花数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复