设为首页 加入收藏

TOP

[LeetCode]Divide Two Integers
2015-07-20 17:24:36 来源: 作者: 【 】 浏览:2
Tags: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;
	}
}



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++ 临时对象 笔记 下一篇LeetCode--Recover Binary Search..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C 内存管理 | 菜鸟教 (2025-12-26 20:20:37)
·如何在 C 语言函数中 (2025-12-26 20:20:34)
·国际音标 [ç] (2025-12-26 20:20:31)
·微服务 Spring Boot (2025-12-26 18:20:10)
·如何调整 Redis 内存 (2025-12-26 18:20:07)