2013.12.7 04:52
Divide two integers without using multiplication, division and mod operator.
Solution:
Another bit-manipulation problem, integer division. Normally if we calculate x / y (x, y > 0), we'll subtract y from x until y < x. This operation can be accelerated if we subtract x << (..., 2, 1, 0) from y, until x < y, using only log2(x) time.
Time complexity is O(log(dividend) - log(divisor)), space complexity is O(1).
Accepted code:
1 // 2RE, 2WA, 1AC 2 class Solution { 3 public: 4 int divide(int dividend, int divisor) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 // 2RE here, -2147483648 is a tricky case 8 9 long long int div1, div2; 10 int s1, s2; 11 long long int base; 12 // 1WA here, $r overflows, must be long long int 13 long long int res, r; 14 15 s1 = sign(dividend); 16 s2 = sign(divisor); 17 18 if(s1 * s2 == 0){ 19 return 0; 20 } 21 22 div1 = dividend > 0 ? dividend : -(long long int)dividend; 23 div2 = divisor > 0 ? divisor : -(long long int)divisor; 24 25 base = div2; 26 r = 1; 27 while(base <= div1){ 28 base <<= 1; 29 r <<= 1; 30 } 31 32 res = 0; 33 while(r > 0){ 34 if(div1 >= base){ 35 div1 -= base; 36 res += r; 37 } 38 base >>= 1; 39 r >>= 1; 40 } 41 42 if(s1 < 0){ 43 res = -res; 44 } 45 if(s2 < 0){ 46 res = -res; 47 } 48 49 // 1WA here, forgot to multiply sign variables 50 return res; 51 } 52 private: 53 int sign(int x){ 54 if(x > 0){ 55 return 1; 56 }else if(x < 0){ 57 return -1; 58 }else{ 59 return 0; 60 } 61 } 62 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)