水仙花数(3位水仙花、100-999之内的所有水仙花、三位及以上水仙花)

问题描述

水仙花数是指一个3位数,它的每个位上的数字的3次幂之和等于它本身,例如:13+53+3^3=153。

3位水仙花

  • 代码
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);   
    System.out.print("请输入一个100~999之间的整数:");
    int n=sc.nextInt();
    if(n>=100) {
       int a=n%10;   //个位
       int b=n/10%10;//十位
       int c=n/100;  //百位
       if(Math.pow(a, 3)+Math.pow(b, 3)+Math.pow(c, 3)==n) {
          System.out.println("该数字是水仙花数");
       }else {
          System.out.println("该数字不是水仙花数");
       }
    }
 }
}

  • 运次结果
    在这里插入图片描述

输出100-999之内的所有水仙花

  • 代码
public class Main {
    public static void main(String[] args) {
         for(int i = 100;i <= 999;i++) {    
             int a=i%10;
             int b=i/10%10;
             int c=i/100;
             if(Math.pow(a, 3)+Math.pow(b, 3)+Math.pow(c, 3)==i) {
                 System.out.println(i);
              }
           }
      }
}

  • 运行结果
    在这里插入图片描述

四叶玫瑰数(三位及以上)

  • 代码
public class Main {
    public static void main(String[] args) {
         Scanner sc=new Scanner(System.in);
         System.out.print("输入一个三位以上的数字:");
         int n=sc.nextInt();
         int sum=0,count=0;
         int temp=n,m=n;
         while(temp!=0) {
              temp=temp/10;
              count++;
         }
         for (int i = 0; i < count; i++) {
             int a=n%10;
              n=n/10;
              sum=(int) (sum+Math.pow(a, count));
          }
          if(sum==m) {
             System.out.println("该数字是水仙花数");
          }else {
             System.out.println("该数字不是水仙花数");
          }
    }
}
  • 运行结果
    在这里插入图片描述

代码重点解析

Math.pow(底数, 指数)Math.pow(a, 3);等价于   a*a*a;

  • 37
    点赞
  • 171
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值