Divide Two Integers
来源:互联网 发布:淘宝装修服务市场 编辑:程序博客网 时间:2024/06/02 04:50
Description:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
问题描述
实现整数除法
思路:
这是一道考察基本功的好题目,包括int型数值范围,处理数值计算的思路,以及细心。
Code:
public class Solution { public int divide(int dividend, int divisor) { if (divisor == 0) { return dividend >= 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; } if (dividend == 0) { return 0; } if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } boolean isNegative = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0); long a = Math.abs((long)dividend); long b = Math.abs((long)divisor); int res = 0; while (a >= b){ int shift = 0; while (a >= b << shift){ shift++; } a -= b << (shift -1); res += 1 << (shift - 1); } return isNegative ? -res : res; }}
注意坑
这里的内循环找到超过b的最大数后,要减去(shift - 1)的2的幂。
另外在用绝对值处理的时候,用 Math.abs(long E)处理Integer.MIN_VALUE情况。防止 overflow….
0 0
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- LeetCode28:Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- Divide Two Integers
- 【leetcode】Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- [LeetCode]Divide Two Integers
- Divide Two Integers
- LeetCode-Divide Two Integers
- Divide Two Integers
- 25 - Divide Two Integers
- 51nod 1002 数塔取数问题(基础dp)
- 一个例子深入下join
- Hibernate框架初学笔记
- Problem B: 求个最大值
- PART 4
- Divide Two Integers
- elasticsearch 组合查询
- SpringBoot-@Schedule定时任务
- windows配置环境变量无效
- python接口调用已训练好的caffe模型测试分类
- 【转】ionic run android 成功launch success,但是genymotion虚拟机没有显示
- Spring源码学习第一节
- Problem C: 数量的类模板
- [C++]条件编译——#if #ifdef 的作用