Given a positive integer num, write a function which returns True if num is a perfect square else False. 给出一个正整数,写一个函数,若该数为完全平方数,则返回True;否则返回False。 Note: Do not use any built-in library function such as sqrt. 不能使用内建函数,如sqrt。 Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
(1)1+3+5+7+.+(2*n-1) = n^2 (2)完全平方数的末位一定为0,1,4,5,6,9中的一个。
class Solution {
public:
bool isPerfectSquare(int num) {
int rest = num % 10;
if(rest == 2 || rest == 3 || rest == 7 || rest == 8)
return false;
int sum = 0;
for(int i = 1; sum < num; i = i + 2){
sum += i;
if(sum == num)
return true;
}
return false;
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有