29. Divide Two Integers(C++)

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

 

 

solution:

复制代码
 1 class Solution {
 2 public:
 3     int divide(int dividend, int divisor) {
 4         int count=0;
 5         if (!divisor || (dividend == INT_MIN && divisor == -1))
 6             return INT_MAX;
 7         int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
 8         long long dvd = labs(dividend);
 9         long long dvs = labs(divisor);
10         while(dvd>=dvs){
11             long long tmp=dvs,mult=1;
12             while(dvd>=(tmp<<1)){
13                 tmp=tmp<<1;
14                 mult=mult<<1;
15             }
16             dvd-=tmp;
17             count+=mult;
18         }
19         return sign==1?count:-count;
20     }
21 };
复制代码

 

posted @   DevinGu  阅读(249)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示