leetCode练习(69)
2016-10-13 20:27
260 查看
题目:Sqrt(x)
难度:medium
问题描述:
Implement
Compute and return the square root of x.
Subscribe to see which companies asked this question
解题思路:
求平方根。首先想到从1到n以此检测I*I是否大于x。但若x很大,需要遍历很多项,速度慢、因此想到二分搜索来计算。
确定了计算方法,这道题解决了一小半。真正的难点在于边界问题。如果x为int的极大左右,那么二分的起点 (x/2)的平方已经超出整数界限,需要主要超限问题。
具体代码如下:
难度:medium
问题描述:
Implement
int sqrt(int x).
Compute and return the square root of x.
Subscribe to see which companies asked this question
解题思路:
求平方根。首先想到从1到n以此检测I*I是否大于x。但若x很大,需要遍历很多项,速度慢、因此想到二分搜索来计算。
确定了计算方法,这道题解决了一小半。真正的难点在于边界问题。如果x为int的极大左右,那么二分的起点 (x/2)的平方已经超出整数界限,需要主要超限问题。
具体代码如下:
public static int mySqrt(int x) { int head=1; int tail=x; int last=-1; int temp; int ji; if(x==0){ return 0; } if(x==Integer.MAX_VALUE){ return 46340; } while(true){ temp=(tail+head)/2; if(temp>50000){ tail=50000; last=50000; continue; } ji=temp*temp; if(ji==x){ return temp; }else if(ji>x||ji<0){ if((temp-last)==1||(temp-last)==0){ return last; } last=temp; tail=temp; continue; }else{//ji<x if((last-temp)==1||(last-temp)==0){ return temp; } last=temp; head=temp; continue; } } }
相关文章推荐
- LeetCode练习-求二叉树的深度-Maximu Depth of Binary Tree
- [leetcode] 69.Sqrt(x)
- 数据结构与算法 LeetCode编程练习--Search in Rotated array
- Leetcode练习<十二> 判断整数是否为回文
- LeetCode 69. Sqrt(x) 解题报告
- leetcode 69. Sqrt(x)
- leetCode练习(54)
- Leetcode练习<二十二> 合并排序好的链表
- leetcode练习 Reconstruct Itinerary
- leetCode练习(72)
- leetCode练习(73)
- leetCode练习(79)
- The Solution to LeetCode 69 Sqrt(x)
- LeetCode练习-动态规划算法-word-break
- LeetCode 69 - Sqrt(x)
- LeetCode Online Judge 题目C# 练习 - Reverse Nodes in k-Group
- LeetCode Online Judge 题目C# 练习 - Two Sum
- Leetcode编程练习:Arithmetic Slices
- [LeetCode] 69. Sqrt(x)
- 69.广搜练习: 最少转弯问题(TURN)