Valid Perfect Square

本文介绍了一种不使用内置平方根函数来判断一个正整数是否为完全平方数的方法。通过两种算法实现:二分查找(Binary Search)和通过迭代检查每个可能的因数。这两种方法都避免了直接使用平方根函数,提供了高效且简洁的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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

 

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

思路1:Binary Search, Accepted.

class Solution {
    public boolean isPerfectSquare(int num) {
        if(num < 0) throw new IllegalArgumentException("num must be positive");
        int start = 0; int end = num;
        while(start<=end){
            int mid = start+(end-start)/2;
            if(Math.pow(mid,2) == num){
                return true;
            } else if(Math.pow(mid,2) > num){
                end = mid-1;
            } else { // Math.pow(mid,2) < num;
                start = mid+1;
            }
        }
        return false;
    }
}

思路2:一种收缩上限的方法,那就是num/i,搜索1到sqrt(num)的上线,这里并没有用sqrt,而是用了除法。很巧妙。

i<=num/i, 实际上i的取值范围是1~ sqrt(num);

class Solution {
    public boolean isPerfectSquare(int num) {
        if(num < 0) throw new IllegalArgumentException("Num must be positive");
        if(num == 0 || num == 1) return true;
        for(int i=1; i<=num/i; i++){
            if( i*i == num){
                return true;
            }
        }
        return false;
    }
}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值