【leetcode】Divide Two Integers
来源:互联网 发布:网络空间安全专业排名 编辑:程序博客网 时间:2024/06/16 03:19
题目:
Divide two integers without using multiplication, division and mod operator.
解析:不使用乘号、除号和余号实现两个整数的除法。该题可以利用移位操作数求解,主要分为三个步骤:
(1)先求两个int类型整数的绝对值,注意要将int类型转化成long类型才能求绝对值:因为int类型的范围是-2147483648~2147483647,如果某个数为-2147483648,其绝对值会溢出。
(2)对被除数a和除数b进行移位除法,主要思路是 a = b *(2^31) * x31+ b *(2^30) * x30 + ... + b * x0,除法的结果为 x31x30...x0,xi表示32位数字中第i位上的数字(0或者1)
(3)最后通过异或和移位判断结果是否带有负号。
Java AC代码:
public class Solution {public int divide(int dividend, int divisor) {long a = Math.abs((long) dividend);long b = Math.abs((long) divisor);long res = 0;for (int i = 31; i >= 0; i--) {if (a >> i >= b) {res += 1 << i;a -= b << i;}}return (int) (((dividend ^ divisor) >> 31) == 0 ? (res) : (-res));}}
0 0
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- 【leetcode】Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode-Divide Two Integers
- LeetCode: Divide Two Integers
- Divide Two Integers - leetcode
- Leetcode: Divide Two Integers
- LeetCode:Divide Two Integers
- leetcode Divide Two Integers
- LeetCode Divide Two Integers
- LeetCode | Divide Two Integers
- Leetcode: Divide Two Integers
- Divide Two Integers -- LeetCode
- 时间序列一般概念
- 点击爱心跳转问题。ajax,跳转到页面顶部
- 滚动视图(UIScrollView)无限无缝左右切换图片,自动顺序加逆序循环播放图片
- stack使用与简单实现
- selector的用法
- 【leetcode】Divide Two Integers
- 李开复:算法的力量 (完整版)
- 【算法】贪心策略实现部分背包问题
- 关于Loadrunner11破解的各种问题。。。泪奔。。。
- 在VMware中安装Linux
- MATLAB知识小结
- 你真的懂单链表吗
- 链式stack
- iBATIS事务