• java笔试题:找出3~999的水仙花数的三种实现方式


    第一种方式:

    package test;
    
    public class Exsercise {
        
        public static void main(String[] args) {
            int sum;
            System.out.println("100~999之间的水仙花数为:");
            for (int i = 100; i <= 999; i++) {
                sum = getCubic(i/100) + getCubic((i/10)%10) + getCubic(i%10);
                if(sum == i){
                    System.out.print(i + " ");
                }
            }
        }
        
        public static int getCubic(int num){
            num = num * num * num;
            return num;
        }
    }

    结果视图:

    第二种方式:while语句

    package test;
    
    public class Exsercise {
        
        public static void main(String[] args) {
            int sum;
            int i = 100;
            System.out.println("100~999之间的水仙花数为:");
            while(i < 1000){
                sum = getCubic(i/100) + getCubic((i/10)%10) + getCubic(i%10);
                if (sum == i) {
                    System.out.print(i + " ");
                }
                i++;
            }
        }
        
        public static int getCubic(int num){
            num = num * num * num;
            return num;
        }
    }

    结果视图:

     

    第三种方式:do……while语句:

    package test;
    
    public class Exsercise {
        
        public static void main(String[] args) {
            int sum;
            int i = 100;
            System.out.println("100~999之间的水仙花数为:");
            do{
                sum = getCubic(i/100) + getCubic((i/10)%10) + getCubic(i%10);
                if (sum == i) {
                    System.out.print(i + " ");
                }
                i++;
            }while(i<1000);
        }
        
        public static int getCubic(int num){
            num = num * num * num;
            return num;
        }
    }

    结果展示:

    好了,欢迎优化改进!

  • 相关阅读:
    触发器trigger
    VS UFT-8 保存该文件将不会保留原始内容
    SQL SERVER 单个用户模式
    vue functional函数式组件
    一维数组转树形结构
    题解 P1081 【开车旅行】
    题解 P5022 【旅行】
    题解 P2296 【寻找道路】
    题解 P2052 【[NOI2011]道路修建】
    题解 P2342 【叠积木】
  • 原文地址:https://www.cnblogs.com/superdrew/p/9736754.html
Copyright © 2020-2023  润新知