How to compute the square root of an integer?
2013-11-19 03:57
459 查看
This is a binary search problem, but it's very easy to get the wrong answer...
Here is the code I wrote for leetcode testing. There still long way to go to understand this 100%...
public class Solution {
public int sqrt(int x) {
if(x ==0 || x== 1) return x;
if(x < 0) return -1;
long start = 0;
long end = x;
while(end-start >= 0){
long mid = start + (end - start)/2;
long midsqr = mid * mid;
if(midsqr == x)
return (int)mid;
else if(midsqr < x){
start = mid+1;
}
else if(midsqr > x){
end = mid - 1;
}
}
return (int) end;
}
}
Here is the code I wrote for leetcode testing. There still long way to go to understand this 100%...
public class Solution {
public int sqrt(int x) {
if(x ==0 || x== 1) return x;
if(x < 0) return -1;
long start = 0;
long end = x;
while(end-start >= 0){
long mid = start + (end - start)/2;
long midsqr = mid * mid;
if(midsqr == x)
return (int)mid;
else if(midsqr < x){
start = mid+1;
}
else if(midsqr > x){
end = mid - 1;
}
}
return (int) end;
}
}
相关文章推荐
- How to get Full Rom Dump / Stock ROM of MT6572 MediaTek Smartphones using SPFT and MTK Droid Root an
- How to find number of a specific integer in an array of Fixnums ruby
- Bad attempt to compute absolute value of signed 32-bit random integer
- leetCode Given an integer (signed 32 bits), write a function to check whether it is a power of 4
- Siebel Symbolic URL: How to configure Displaying External Content Outside of an Applet
- How to get an icon of an object in Windchill
- Ten Ways to Check if an Integer Is a Power Of Two in C
- How to change the size of the button of an android checkbox?
- How to combine the value of multiple hashes within an array by the same key
- An example of how to do a simulation by LAMMPS
- How to Build an High Availability MQTT Cluster for the Internet of Things
- Siebel Symbolic URL: How to configure Displaying External Content Outside of an Applet
- How to build the topology of an OSPF area
- How to use Fiddler and HTTP replay to have an offline copy of your site
- How to change to an older version of node.js
- how to generate an analog output from a in-built pwm of Atmega 32AVR microcontrloller?
- how to calculate the textsize of TLatex in CernRoot
- How to access pixel data of an image
- 关于FindBug-Bad attempt to compute absolute value of signed random integer
- How to configure the Virtual Path of ASP.NET Development Server to be “Root”