0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode日本語修行15日目- [633-平方数の総和]

Posted at

###Sum of Square Numbers
参考:https://leetcode.com/problems/sum-of-square-numbers/
###問題の内容:
非負の整数c、a2+b2=cの条件を満足の整数a、bがあるかどうかを判断する。

###例:
例1:
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5

例2:
Input: c = 3
Output: false
###ヒント:
0 <= c <= 231 - 1


この問題は、普通のループを使って、解決できますが、
DoublePointerを使う方がいいと思います。
条件は:
0 <= aa + bb <= c
0 <= a,b <= sqrt(c)

class Solution {
    fun judgeSquareSum(c: Int): Boolean {
        var a = 0
        var b = Math.sqrt(c.toDouble()).toInt()
        while(a <= b){
            when{
                a * a + b * b == c -> return true
                a * a + b * b > c -> b--
                else -> a++
            }
        }
        return false
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?