zoukankan      html  css  js  c++  java
  • 牛客网在线编程:水仙花数

    题目:

    春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的: “水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,
    比如:153=1^3+5^3+3^3。 现在要求输出所有在m和n范围内的水仙花数。
    输入描述:
    输入数据有多组,每组占一行,包括两个整数m和n(100 ≤ m ≤ n ≤ 999)。
    输出描述:
    对于每个测试实例,要求输出所有在给定范围内的水仙花数,就是说,输出的水仙花数必须大于等于m,并且小于等于n,如果有多个,则要求从小到大排列在一行内输出,
    之间用一个空格隔开;
    如果给定的范围内不存在水仙花数,则输出no;
    每个测试实例的输出占一行。
    示例1
    输入

    100 120
    300 380
    输出

    no
    370 371

    思路:

    判断水仙花数,使用Math.pow()计算次方数。
    输出时设定flag,判断水仙花数是否存在。注意只有一行输出,多个输出值间加空格。使用system.out.print()而不是println().

     1 import java.util.Scanner;;
     2 public class Shuixianhua {
     3 
     4     public static boolean isShuixianhua(int n){
     5         int a,b,c;
     6         a = n/100;
     7         b = (n%100)/10;
     8         c = n-a*100-b*10;
     9 //        System.out.println(a);
    10 //        System.out.println(b);
    11 //        System.out.println(c);
    12         if(n==Math.pow(a, 3)+Math.pow(b, 3)+Math.pow(c, 3)){
    13             return true;
    14         }
    15         return false;
    16     }
    17     public static void main(String[] args) {
    18         Scanner sc = new Scanner(System.in);
    19         String res = "no";
    20         while(sc.hasNext()){
    21             int m = sc.nextInt();
    22             int n = sc.nextInt();
    23             //System.out.println(m);
    24             //System.out.println(n);
    25             int flag = 0;
    26             for(int i = m;i<=n;i++){
    27                 if(isShuixianhua(i)){
    28                     flag ++;
    29                     if(flag==1){
    30                         System.out.print(i);
    31                     }else{
    32                         System.out.print(" "+i);
    33                     }
    34                 }
    35             }
    36             if(flag ==0){System.out.println("no");}
    37         }        
    38     }
    39 
    40 }
  • 相关阅读:
    jqgrid 获取选中用户的数据插入
    jqgrid 自定义文本框、选择框等查询
    Java学习—— for循环
    Android中 Http请求
    异步消息处理机制——Handler用法
    ThreadLocal
    Android开发 学习笔记——HelloWorld
    eclipse 常用插件
    mysql 命令备份还原
    学习
  • 原文地址:https://www.cnblogs.com/zlz099/p/8509496.html
Copyright © 2011-2022 走看看