29. Divide Two Integers
来源:互联网 发布:恺英网络借壳泰亚股份 编辑:程序博客网 时间:2024/06/17 22:55
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
不使用乘法、除法和取余操作实现两数相除。
若数值溢出,返回MAX_INT.
#include "limits.h"#include <algorithm>int DivideTwoIntegers::divide(int dividend, int divisor){ //数值需要是long long 类型 //因为输入的都是int型,比如被除数是-2147483648,在int范围内,当除数是-1时,结果就超出了int范围,需要返回INT_MAX if (divisor == 0 || (dividend == INT_MIN && divisor == -1)) return INT_MAX; long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0; //从最大倍数开始减,实现O(logN)的时间复杂度 while (m >= n) { //t做为临时变量,将被左移扩展至不超过m的最大倍数 long long t = n, p = 1; while (m >= (t << 1)) { t <<= 1; p <<= 1; } res += p; m -= t; } //注意符号问题 if ((dividend < 0) ^ (divisor < 0)) res = -res; return res;}
阅读全文
0 0
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- C语言-位操作技巧
- 集合源码学习(三):ArrayList
- keepalived+LVS/DR
- 1227 方格取数 2 费用流
- 用proteus来仿真二极管与门电路
- 29. Divide Two Integers
- Flash as3 正则表达式
- ubuntu php7 mysqlli不存在解决办法
- libevent源码学习-----统一事件源及信号绑定函数
- DEBUG参数使用大全
- 做项目的一点心得
- Scanner类
- 初识RAC-002--RACSignal类
- Flash as3资源加载