首页 > 其他分享 >LeetCode 367. 有效的完全平方数

LeetCode 367. 有效的完全平方数

时间:2022-08-22 19:17:47浏览次数:52  
标签:平方 return int mid num 367 true LeetCode

LeetCode 367. 有效的完全平方数

思路:
核心为最后一步判断当二分结束后值为及接近一个整数的浮点数(如2.9xxxx)此时加上极小数(1e-6)取整再平方,若与num相等则为完全平方数

class Solution {
public:
    bool isPerfectSquare(int num) {
        if (num == 0) return true;
        if (num == 1) return true;

        double l = 0, r = num;
        while (r - l > 1e-6) {
            double mid = (l + r) / 2;
            if (mid * mid == num) return true;
            else if (mid * mid > num) r = mid;
            else l = mid;
        }       
        int y = (int)(l + 1e-6);   
        if (y * y == num) return true;
        return false;
    }
};

标签:平方,return,int,mid,num,367,true,LeetCode
From: https://www.cnblogs.com/hjy94wo/p/16613888.html

相关文章

  • LeetCode 69. x 的平方根
    LeetCode69.x的平方根思路:浮点数二分修改版因为返回的是整数所以二分分三类讨论mid*mid==x该情况mid为x的平方根mid*mid>x该情况mid大于x的平方根mid......
  • LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置
    34.在排序数组中查找元素的第一个和最后一个位置思路:与AcWing789一致classSolution{public:vector<int>searchRange(vector<int>&nums,inttarget){......
  • LeetCode 35. 搜索插入位置
    LeetCode35.搜索插入位置思路直接利用二分模板注意右指针开始为nums.size()而不是nums.size()-1因为有可能在最后一位插入classSolution{public:intsearc......
  • [Google] LeetCode 1937 Maximum Number of Points with Cost
    Youaregivenanmxnintegermatrixpoints(0-indexed).Startingwith0points,youwanttomaximizethenumberofpointsyoucangetfromthematrix.Togai......
  • LeetCode 811. Subdomain Visit Count
    原题链接在这里:https://leetcode.com/problems/subdomain-visit-count/题目:Awebsitedomain "discuss.leetcode.com" consistsofvarioussubdomains.Atthetople......
  • [Google] LeetCode 729 My Calendar I
    Youareimplementingaprogramtouseasyourcalendar.Wecanaddaneweventifaddingtheeventwillnotcauseadoublebooking.Adoublebookinghappenswh......
  • LeetCode 1472. Design Browser History
    原题链接在这里:https://leetcode.com/problems/design-browser-history/题目:Youhavea browser ofonetabwhereyoustartonthe homepage andyoucanvisitan......
  • [Google] LeetCode 2013 Detect Squares
    YouaregivenastreamofpointsontheX-Yplane.Designanalgorithmthat:Addsnewpointsfromthestreamintoadatastructure.Duplicatepointsareallow......
  • [Google] LeetCode 1048 Longest String Chain
    YouaregivenanarrayofwordswhereeachwordconsistsoflowercaseEnglishletters.\(word_A\)isapredecessorof\(word_B\)ifandonlyifwecaninserte......
  • 69. x 的平方根
    69.x的平方根给你一个非负整数x,计算并返回 x 的算术平方根。由于返回类型是整数,结果只保留整数部分,小数部分将被舍去。注意:不允许使用任何内置指数函数......