Leetcode 633. Sum of Square Numbers(Easy)

1.题目

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.

翻译:给定一个非负整数 c ,你的任务是判断是否有两个整数 a 和 b ,使得a2 + b2 = c.

Example 1:

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: 3
Output: False

2.思路

超时思路:比较容易想到的就是,两层的循环,外侧循环 i 的区间是0到根号c,里层循环 j 的区间是 i到根号c。我已经尽力缩小区间,然而还是超时了。

AC思路:之前有一个 回文判断 的题,是这样的思路,保留外层循环,然后逆向思维,看看剩下的数(c-i2)能不能被开根号。这样就只需要一层循环。判断数a能否被完全开方的方法就是,a开根号取整,再平方 是否和a相等。

3.算法

class Solution {
    public boolean judgeSquareSum(int c) {
        int sub=0;
        int pow;
        for(int i=0;i<=Math.sqrt(c);i++){
            sub=c-(int)Math.pow(i,2);
            pow=(int)Math.pow((int)Math.sqrt(sub),2);
            if(pow==sub){
                return true;
            }    
        }
        return false;
    }
}

4.总结

Math.sqrt()和Math.pow()返回值都是double,要强制转换成int,不然会提示报错。

猜你喜欢

转载自blog.csdn.net/crab0314/article/details/79724278