LeetCode 69. Sqrt(x)
来源:互联网 发布:java注解原理 编辑:程序博客网 时间:2024/06/08 18:26
题目:
Implement int sqrt(int x).
Compute and return the square root of x.
思路:
写一个自己的求平方根的函数。
初始化low为0,high为x,mid为(high-low)/2+low。如果mid的平方不为x,如果mid的平方大于x面mid-1的平方小于x,直接返回mid-1,其实是没有平方根,就返回小的数;如果mid的平方大于x,更新high为mid-1,更新mid;如果mid的平方小于x,更新low为mid+1,更新mid。循环结束如果没有返回,则mid即为正确的平方根。
代码:
class Solution {public: int mySqrt(int x) { int low=0;//初始化low为0,high为x int high=x; int mid=(high-low)/2+low;//mid为(high-low)/2+low while(pow(mid,2)!=x){//如果mid的平方不为x if(pow(mid,2)>x&&pow(mid-1,2)<x){//如果mid的平方大于x面mid-1的平方小于x return mid-1;//直接返回mid-1,其实是没有平方根,就返回小的数 } else if(pow(mid,2)>x){//如果mid的平方大于x high=mid-1;//更新high为mid-1,更新mid mid=(high-low)/2+low; } else if(pow(mid,2)<x){//如果mid的平方小于x low=mid+1;//更新low为mid+1,更新mid mid=(high-low)/2+low; } } return mid;//循环结束如果没有返回,则mid即为正确的平方根 }};
输出结果: 9ms
0 0
- LeetCode 69. Sqrt(x)
- LeetCode 69.Sqrt(x)
- LeetCode --- 69. Sqrt(x)
- [Leetcode] 69. Sqrt(x)
- [leetcode] 69.Sqrt(x)
- Leetcode-69.Sqrt(x)
- leetcode--69.sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- 【LeetCode】69. Sqrt(x)
- 69. Sqrt(x) LeetCode
- [leetcode] 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode-69. Sqrt(x)
- [leetcode]69. Sqrt(x)
- LeetCode-69.Sqrt(x)
- 子页面通过js获取获控制父页面
- 动态规划 06题
- c++memset函数的使用方法
- JS实现的数字千分位符格式化方法
- 冒泡排序学习
- LeetCode 69. Sqrt(x)
- js遇到的若干问题
- 经典线程同步总结 关键段 事件 互斥量 信号量
- 安卓开发,高德地图5.0版本导航部分手机出现白屏
- 虚数的意义
- CentOS6.5安装Qt4.8.6+QtCreator2.6.1
- matlab读取视频VideoReader类
- js中数组Array的一些常用方法总结
- 网络基础知识-OSI七层模型