1. 程式人生 > >【LeetCode】633. 平方數之和(Sum of Square Numbers)

【LeetCode】633. 平方數之和(Sum of Square Numbers)

英文練習 | 中文練習

題目描述: 給定一個非負整數 c ,你要判斷是否存在兩個整數 a 和 b,c 等於 a 和 b 的平方和。

示例:

輸入: 5
輸出: True
解釋: 1 * 1 + 2 * 2 = 5

解法一: 利用雙指標的思想,需要注意兩個坑點,一個是 a 可能等於 b ,第二個是 a 和 b 可能為 0 。b 的起始位置為 Math.sqrt(c)

public boolean judgeSquareSum(int c) {
    int a = 0, b = (int)Math.sqrt(c);
    while(a <= b)
{ int ans = a * a + b * b; if(ans == c){ return true; }else if(ans > c){ b--; }else if(ans < c){ a++; } } return false; }

解法二: 用根號替換搜尋結果的方法。

public boolean judgeSquareSum(int c) {
    for (long a = 0; a *
a <= c; a++) { double b = Math.sqrt(c - a * a); if (b == (int) b) return true; } return false; }