★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-umvzmgyi-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a2 + b2 = c.git
Example 1:github
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:微信
Input: 3 Output: False
給定一個非負整數 c
,你要判斷是否存在兩個整數 a
和 b
,使得 a2 + b2 = c。ide
示例1:spa
輸入: 5 輸出: True 解釋: 1 * 1 + 2 * 2 = 5
示例2:code
輸入: 3 輸出: False
1 class Solution { 2 func judgeSquareSum(_ c: Int) -> Bool { 3 var a:Int = 0 4 var b:Int = Int(sqrt(Double(c))) 5 while (a <= b) 6 { 7 if a * a + b * b == c 8 { 9 return true 10 } 11 else if a * a + b * b < c 12 { 13 a += 1 14 } 15 else 16 { 17 b -= 1 18 } 19 } 20 return false 21 } 22 }
8mshtm
1 class Solution { 2 func judgeSquareSum(_ c: Int) -> Bool { 3 var c = c; var i = 2 4 while (i*i <= c) { 5 var multi = 0 6 if (c % i == 0) { 7 while (c % i == 0) { 8 multi += 1 9 c /= i 10 } 11 if (i % 4 == 3 && multi % 2 != 0) { 12 return false 13 } 14 } 15 i += 1 16 } 17 return c % 4 != 3 18 } 19 }
12msblog
1 class Solution { 2 func judgeSquareSum(_ c: Int) -> Bool { 3 var left = 0 4 var right: Int = Int(sqrt(Double.init(exactly: c)!)) 5 while left <= right { 6 let cur = left*left + right*right 7 if cur == c { 8 return true 9 } 10 11 if cur < c { 12 left += 1 13 } else { 14 right -= 1 15 } 16 } 17 return false 18 } 19 }
24msci
1 class Solution { 2 func judgeSquareSum(_ c: Int) -> Bool { 3 let root = Int(sqrt(Double(c))) 4 5 for i in 0...root { 6 let diff = c - i * i 7 let diffRoot = sqrt(Double(diff)) 8 9 if Double(Int(diffRoot)) == diffRoot { 10 return true 11 } 12 } 13 14 return false 15 } 16 }
28ms
1 class Solution { 2 func judgeSquareSum(_ c: Int) -> Bool { 3 for a in 0...Int(sqrt(Double(c))) { 4 let b = Int(sqrt(Double(c - a * a))) 5 if a * a + b * b == c { 6 return true 7 } 8 } 9 return false 10 } 11 }