[leetcode]Divide Two Integers
来源:互联网 发布:淘宝退换货规则 编辑:程序博客网 时间:2024/06/05 15:39
题目:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
描述:实现除法,要求不能使用乘法、除法、取模,注意可能存在溢出
solution by python:
写的略乱。。。
maxint = 2147483647minint = -2147483648class Solution: # @return an integer def divide(self, dividend, divisor): if divisor == 0: return maxint if divisor == 1: return dividend if divisor == -1: return -dividend if dividend != minint else maxint if dividend>0 and divisor<0 or dividend<0 and divisor>0: ans = self.divide(abs(dividend), abs(divisor)) return -ans if ans!=minint else maxint dividend = abs(dividend);divisor=abs(divisor) ans = 0 while dividend >= divisor: b = 1;d=divisor while d < dividend>>1: d <<= 1 b <<= 1 ans += b dividend -= d return anssolution by c++:
class Solution {public: int divide(int dividend, int divisor) { bool negative = false; if(dividend>0 && divisor<0 || dividend<0 && divisor>0) negative = true; long long dvd = dividend; long long dvs = divisor; long long ans = absDivide( abs(dvd), abs(dvs)); if(negative) return 0-ans; return ans; } long long absDivide(long long dividend, long long divisor) { if(dividend < divisor) return 0; long long ans = 1; long long a = divisor; while(a <= dividend) { ans <<= 1; a <<= 1; } ans >>= 1; a >>= 1; return ans+absDivide(dividend-a, divisor); }};
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
- 【COCOS2DX-LUA 脚本开发之六】利用Lua强转函数解决使用CCNode报错或无法正常使用以及简单介绍 quick-cocos2d-x 与 OpenQuick 两款Lua免费开源框架
- timus 2021. Scarily interesting!(提示)
- list/map中安全删除元素
- Delphi XE6 学习笔记(9)手动填充ListView及ListBox
- Cocos2d-x CCNotificationCenter
- [leetcode]Divide Two Integers
- css 模板
- Struts2整合 Freemarker 实例
- 以插件目录方式从本地安装Eclipse插件
- sqlserve 数据类型详解
- 云服务PHP读取XML问题失败的问题解决方法
- C++标准库---count()&count_if()
- android刷新控件的使用(下拉和上拉刷新)
- wBox FancyBox window.open Demo