0
点赞
收藏
分享

微信扫一扫

从零开始学cv-5: 图像的仿射变换

Separes 2024-08-22 阅读 36

 一、题目概述

二、思路方向 

三、代码实现 

public class Solution {  
    public int mySqrt(int x) {  
        if (x == 0) {  
            return 0;  
        }  
  
        long left = 1, right = x; // 使用long类型避免平方时溢出  
        while (left <= right) {  
            long mid = left + (right - left) / 2; // 防止溢出  
            long square = mid * mid;  
  
            if (square == x) {  
                return (int) mid;  
            } else if (square < x) {  
                left = mid + 1;  
            } else {  
                right = mid - 1;  
            }  
        }  
  
        // 当left > right时,循环结束,right为最接近x的平方根的整数(向下取整)  
        return (int) right;  
    }  
  
    public static void main(String[] args) {  
        Solution solution = new Solution();  
        int x = 9;  
        System.out.println("The square root of " + x + " is " + solution.mySqrt(x));  
  
        x = 8;  
        System.out.println("The square root of " + x + " is " + solution.mySqrt(x));  
    }  
}

执行结果: 

四、小结

 结语  

举报

相关推荐

0 条评论