标签:
int sqrt(int x) { int low = 0; int high = x; int mid = 0;; while(low <= high) { mid = (high - low)/2 + low; cout << "low\t" << low << endl; cout << "high\t" << high<< endl; cout << "mid\t" << mid<< endl; if(x == INT_MAX) break; if( (mid * mid) <= x && (mid+1) * (mid+1) > x) return mid; else if(mid * mid < x ) { low = mid + 1; } else { high = mid - 1; } } return mid; }
然后给出一个AC版本,用mid<x/mid 来代替,同时由于有除法,要保证mid不等于0,当x==1时,mid就会为0,所以特殊处理,当x》=2时,mid》=1,就没问题了。
class Solution { public: int sqrt(int x) { int low = 0; int high = x; int mid = 0;; if(x == 0) return 0; if(x < 0) return -1; if(x == 1) return 1; while(low <= high) { mid = (high - low)/2 + low; #if 0 cout << "low\t" << low << endl; cout << "high\t" << high<< endl; cout << "mid\t" << mid<< endl; #endif if( mid <= x/mid && (mid+1) > x/(mid+1)) return mid; else if( mid < x/mid ) { low = mid + 1; } else { high = mid - 1; } } return -1; } };
标签:
原文地址:http://www.cnblogs.com/diegodu/p/4325528.html