算法打卡第3天(1道程序员必备题)

前言

每天打卡一道算法题,既是学习的过程,又是养成习惯的过程
算法练习包含最基础的程序员必备题以及LeetCode
今天是算法题打卡第3天!

1、题目描述

一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
完全平方数:指的是一个数可以表示为另一个整数的平方,如0、1、4、9、16等。

2、自己写代码

用Math.sqrt()方法来计算num1、num2的平方根,然后将平方根转为整数类型,并取它的整数部分。将整数平方根与原始数进行比较,如果平方根的平方值与原始数相等,那么说明原始数是一个完全平方数。最后用break来中断循环。
Math.sqrt()用来计算一个数的平方根,,例如:Math.sqrt(25)将返回5.0,因为5的平方是25。

public class a3 {
    public static void main(String[] args) {
        method1();
    }
    public static void method1(){
        for (int x = 1; ; x++){
            int num1 = x + 100;
            int num2 = x + 268;
            int sqrt1 = (int) Math.sqrt(num1);
            int sqrt2 = (int) Math.sqrt(num2);
            if (sqrt1 * sqrt1 == num1 && sqrt2 * sqrt2 == num2){
                System.out.println("符合条件的整数是:"+ x);
                break;
            }
        }
    }
}

3、优化的代码

优化的思路跟自己写的思路是一样的,只是把判断是不是平方数的方法抽出来了。

    public static void method2(){
        for (int x = 0; ; x++){
            if(isPerfectSquare(x+100) && isPerfectSquare(x+268)){
                System.out.println("符合条件的整数是:"+ x);
                break;
            }
        }
    }
    public static boolean isPerfectSquare(int num){
        int sqrt = (int) Math.sqrt(num);
        return sqrt * sqrt == num;
    }

不足之处,欢迎雅正留言!

你可能感兴趣的:(算法,java)