367. Valid Perfect Square

问题链接:https://leetcode.com/problems/valid-perfect-square/

原文:http://www.cnblogs.com/guoguolan/p/5619443.html

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False

解法一:
复制代码
 1 public class Solution {
 2     public boolean isPerfectSquare(int num) {
 3         if(num < 0) return false;
 4         if(num == 1) return true;
 5         for(int i = 1; i<= num/i;i++){
 6             if(i*i == num) return true;
 7         }
 8         return false;
 9     }
10 }
复制代码

解法2:  二分查找法 (java 没有ac 仅供参考)

复制代码
 1 public class Solution {
 2     public boolean isPerfectSquare(int num) {
 3         if(num < 0) return false;
 4         if(num == 1) return true;
 5         int low = 0, high = num/2;
 6         while(low <= high){
 7             long mid = (low + high)/2;
 8             long tmp = mid*mid;
 9             if(tmp == num) return true;
10             if(tmp > num) high = mid - 1;
11             else low = mid + 1;
12         }
13         return false;
14     }
15 }
复制代码

解法3:https://leetcode.com/discuss/110659/o-1-time-c-solution-inspired-by-q_rsqrt   大神的 O(1)  解法。

class Solution {
public:
    bool isPerfectSquare(int num) {
        if (num < 0) return false;
        int root = floorSqrt(num);
        return root * root == num;
    }

    int32_t floorSqrt(int32_t x) {
        double y=x; int64_t i=0x5fe6eb50c7b537a9;
        y = *(double*)&(i = i-(*(int64_t*)&y)/2);
        y = y * (3 - x * y * y) * 0.5;
        y = y * (3 - x * y * y) * 0.5;
        i = x * y + 1; return i - (i * i > x);
    }
};

解法4:

完全平方数是一系列奇数之和,例如:

1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
25 = 1 + 3 + 5 + 7 + 9
36 = 1 + 3 + 5 + 7 + 9 + 11
....
1+3+...+(2n-1) = (2n-1 + 1)n/2 = n*n

 

复制代码
 1 public class Solution {
 2     public boolean isPerfectSquare(int num) {
 3         int i = 1;
 4         while (num > 0) {
 5             num -= i;
 6             i += 2;
 7         }
 8         return num == 0;
 9     }
10 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值