程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode]Divide Two Integers

[LeetCode]Divide Two Integers

編輯:C++入門知識

[LeetCode]Divide Two Integers


Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

時間復雜度 log(n)

有個coner case

dividend = -2147483648

divisor = -1;

答案是2147483647

dividend = -2147483648

divisor = 1

答案是-2147483648 如果把判斷正負放在最後的話就會overflow

public class Solution {
	public int divide(int dividend, int divisor) {
		long a = dividend > 0 ? dividend : -(long)dividend;
		long b = divisor > 0 ? divisor : -(long)divisor;
		int sgn =(((dividend>0&&divisor>0)||(dividend<0&&divisor<0))?1:-1);
		int res = 0;
		while (a >= b) {
			long c = b;
			int i = 1;
			while (a >= c) {
				a -= c;
				if(a>=0){
					res += sgn*(Math.pow(2, i - 1));
				}else{
					break;
				}
				c <<= 1;
				i++;
			}
		}
		return  res;
	}
}



  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved