★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-kxyxogsj-eu.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a positive integer num, write a function which returns True if num is a perfect square else False.git
Note: Do not use any built-in library function such as sqrt
.github
Example 1:微信
Input: 16
Output: true
Example 2:函數
Input: 14
Output: false
給定一個正整數 num,編寫一個函數,若是 num 是一個徹底平方數,則返回 True,不然返回 False。ui
說明:不要使用任何內置的庫函數,如 sqrt
。spa
示例 1:code
輸入:16 輸出:True
示例 2:htm
輸入:14 輸出:False
8ms
1 class Solution { 2 func isPerfectSquare(_ num: Int) -> Bool { 3 //任意徹底平方數均可以表示成連續的奇數和 4 var j:Int = num 5 var i:Int = 1 6 while(j > 0) 7 { 8 j -= i 9 i += 2 10 } 11 return j == 0 12 } 13 }
8msblog
1 class Solution { 2 func isPerfectSquare(_ num: Int) -> Bool { 3 var x = 0 4 while x * x < num { 5 x += 1 6 } 7 8 return x * x == num 9 } 10 }
12ms
1 class Solution { 2 func isPerfectSquare(_ num: Int) -> Bool { 3 var r = num 4 while (r*r > num){ 5 r = (r + num/r)/2 6 } 7 return r*r == num 8 } 9 }
8ms
1 class Solution { 2 func isPerfectSquare(_ num: Int) -> Bool { 3 //二分法 4 var left = 1 5 var right = num 6 7 while left <= right { 8 let mid = left + (right - left) / 2 9 if mid * mid >= num { 10 right = mid - 1 11 } else if mid * mid < num { 12 left = mid + 1 13 } 14 } 15 16 return left * left == num 17 } 18 }