Leetcode--Divide Two Integers
来源:互联网 发布:郑州大学网络教育学费 编辑:程序博客网 时间:2024/06/06 21:03
Problem Description:
Divide two integers without using multiplication, division and mod operator.
分析:题目意思很容易理解,就是不用乘除法和模运算求来做除法,很容易想到的一个方法是一直做减法,然后计数,但是提交之后显示超时,在网上找到一种解法,利用位运算,意思是任何一个整数可以表示成以2的幂为底的一组基的线性组合,即num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n。基于以上这个公式以及左移一位相当于乘以2,我们先让除数左移直到大于被除数之前得到一个最大的基n的值,说明被除数中至少包含2^n个除数,然后减去这个基数,再依次找到n-1,...,1的值。将所有的基数相加即可得到结果。具体代码如下:
class Solution {public: int divide(int dividend, int divisor) { assert(divisor != 0); int res=0; int flag=1; if((dividend<0 && divisor>0)||(dividend>0 && divisor<0)) flag=-1; long long divid=abs((long long)dividend);//考虑对最大最小整数取模的情况 long long divi=abs((long long)divisor); long long temp=0; while(divi<=divid) { int cnt=1; temp=divi; while((temp<<=1)<=divid) { cnt<<=1; } res+=cnt; divid-=(temp>>1); } return (int)res*flag; }};
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
- java.lang.IllegalStateException: You cannot call onTextChanged with a non filterable adapter
- 3.3-多个栈组合模拟一个栈
- struts1源码学习6(doPost和doGet)
- 如何调用DLL
- Jquery json jsp实例
- Leetcode--Divide Two Integers
- 基于gnu-arm-linux的LPC2220的简单工程模板
- HDU 4902 Nice boat(线段树 区间更新)
- ural 1932 The Secret of Identifier (容斥原理)
- HDU 4786 Fibonacci Tree 最小生成树 kruskal算法
- FFT.c
- hdu 1398 Square Coins
- 2014年辛星vim教程秋季版正式完工,特发此贴纪念下
- 国外大牛写的HOOK