leetcode 53: Sqrt(x)
2013-01-26 05:25
375 查看
Sqrt(x)Apr
3 '12
Implement
Compute and return the square root of x.
3 '12
Implement
int sqrt(int x).
Compute and return the square root of x.
class Solution { public: int sqrt(int x) { // Start typing your C/C++ solution below // DO NOT write int main() function // Start typing your Java solution below // DO NOT write main() function if( x <=0 ) return 0; unsigned k = (1<< (sizeof(x)*8 -1)/2 ); int rel = 0; while( k>0) { rel |= k; unsigned t = rel*rel; cout<<'$'<<t<<'$'; if( t > x) { rel -= k; } k >>= 1; } return rel; } };
public class Solution { //-1, 0, 1, 9, 11, MAX_INT, MIN_INT public int sqrt(int x) { // Start typing your Java solution below // DO NOT write main() function if(x<0) return -1; int res = 0; int k = 1<<15; // can only shift 15 bits. if shift 16, will be overflow. while(k>0) { res |= k; if( res * res > x) { res -= k; } k >>= 1; } return res; } }
相关文章推荐
- leetcode 53: Sqrt(x)
- [LeetCode]Sqrt(x)@python
- Leetcode : Sqrt
- leetcode--Sqrt(x)
- Leetcode-Sqrt(x)
- [LeetCode102]Sqrt(x)
- Leetcode 53 Maximum Subarray
- LeetCode 69. Sqrt(x)
- leetcode - Sqrt(x) -- 再看
- [LeetCode]53 Maximum Subarray
- LeetCode题解:Sqrt(x)
- [Leetcode 55] 53 Maximum Subarray
- [leetcode] 69. Sqrt(x)
- LeetCode 69. Sqrt(x) (平方根)
- Leetcode: Sqrt(x)
- leetcode - Sqrt(x)
- LeetCode 53 --- Maximum Subarray
- LeetCode 53/152 Maximum Subarray/Maximum Product Subarray---DP **
- Leetcode: Sqrt(x)
- LeetCode53——Maximum Subarray