Leetcodes Solution 29 Divide Two Integers
匯總
雪之下雪乃:leetcode解題總匯Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路1
使用位運算
比如dividend = 15, divisor = 3
3 右位移4次等於12,5次等於24,15 = 3 * 4 + 3
然後剩下的餘數在用上面的操作,再右位移一次,最後得到的答案是5次
class Solution{public: int divide(int dividend, int divisor){ if(!divisor || dividend == INT_MIN && divisor == -1) return INT_MAX; int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; long long dvd = labs(dividend); long long dvs = labs(divisor); int res = 0; while(dvd >= dvs){ long long temp = dvs, multiple = 1; while(dvd >= (temp << 1)){ temp <<= 1; multiple <<= 1; } dvd -= temp; res += multiple; } return sign == 1 ? res : -res; }};
推薦閱讀:
※【轉】機器學習新手必學十大演算法指南
※無序數組的中第k小的數字
※037 Sudoku Solver[H]
※九章演算法 | Facebook 面試題 : 有手續費的買賣股票問題
※一名業餘選手的2018天梯+藍橋省賽心得體會