Divide Two Integers


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

SOLUTION 1
1. 基本思想是不断地减掉除数,直到为0为止。但是这样会太慢。

2. 我们可以使用2分法来加速这个过程。不断对除数*2,直到它比被除数还大为止。加倍的同时,也记录下cnt,将被除数减掉加倍后的值,并且结果+cnt。

因为是2倍地加大,所以速度会很快,指数级的速度。

3. 另外要注意的是:最小值的越界问题。对最小的正数取abs,得到的还是它。。。 因为最小的正数的绝对值大于最大的正数(INT)

所以,我们使用Long来接住这个集合就可以了。

 public class Solution {
public int divide(int dividend, int divisor) {
long a = Math.abs((long)dividend); // ref : http://blog.csdn.net/kenden23/article/details/16986763
// Note: 在这里必须先取long再abs,否则int的最小值abs后也是原值
long b = Math.abs((long)divisor); int ret = 0;
// 这里必须是= 因为相等时也可以减
while (a >= b) {
// 判断条件是 >=
for (long deduce = b, cnt = 1; a >= deduce; deduce <<= 1, cnt <<= 1) {
a -= deduce;
ret += cnt;
}
} // 获取符号位。根据除数跟被除数的关系来定
return (dividend > 0) ^ (divisor > 0) ? -ret: ret;
}
}

注意:

1. C,java中的右移运算,是带符号位的,叫算术右移http://www.cppblog.com/tx7do/archive/2006/10/19/13867.html

2015.1.3 redo:

Leetcode又加强了一大堆边界条件运算,所以我们代码也要更改:

1. 返回值的时候,判断是不是越界,越界返回最大值。

例子:

Input: -2147483648, -1
Expected: 2147483647

 public int divide(int dividend, int divisor) {
if (divisor == 0) {
return Integer.MAX_VALUE;
} // Note: 在这里必须先取long再abs,否则int的最小值abs后也是原值
long dividendTmp = Math.abs((long)dividend);
long divisorTmp = Math.abs((long)divisor); // bug 3: ret should use Long to avoid overflow.
long ret = 0;
// bug 2: should use dividentTmp > divisor as the while judge.
while (dividendTmp >= divisorTmp) {
// bug 1: should use Long for tmp.
long tmp = divisorTmp;
int rst = 1;
while(tmp <= dividendTmp) {
// bug 3: the two statement should inside the while LOOP.
ret += rst;
dividendTmp -= tmp; tmp <<= 1;
rst <<= 1;
}
}
// bug 4: out of range:
/*
Input: -2147483648, -1
Output: -2147483648
Expected: 2147483647
*/
//ret = ((dividend > 0) ^ (divisor > 0)) ? -ret: ret;
ret = ((((dividend ^ divisor) >> 31) & 1) == 1) ? -ret: ret; if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {
return Integer.MAX_VALUE;
} else {
return (int)ret;
}
}

简化一点:

 public int divide(int dividend, int divisor) {
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor); long ret = 0; while (a >= b) {
for (long tmp = b, cnt = 1; a >= tmp; tmp <<= 1, cnt <<= 1) {
ret += cnt;
a -= tmp;
}
} ret = (((dividend ^ divisor) >> 31) & 1) == 1 ? -ret: ret;
if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {
return Integer.MAX_VALUE;
} return (int)ret;
}

GitHub Code:

divide.java

Ref: http://blog.csdn.net/fightforyourdream/article/details/16899675

LeetCode: Divide Two Integers 解题报告的更多相关文章

  1. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  2. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  3. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  4. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  5. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  6. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

  7. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  8. [LeetCode] Divide Two Integers 两数相除

    Divide two integers without using multiplication, division and mod operator. If it is overflow, retu ...

  9. LeetCode: Unique Paths II 解题报告

    Unique Paths II Total Accepted: 31019 Total Submissions: 110866My Submissions Question Solution  Fol ...

随机推荐

  1. Flash builder 调试技巧 (分享)

    如果这个Flash能直接自己运行,例如Air或者简单不依赖于外部网页的flash,当然非常容易调试.直接F11嘛~~~   但是,如果这个Flash要依赖于外部环境才能运行,那该怎么调试呢?   核心 ...

  2. Swift Modules for React Native

    React Native is an Objective-C application framework that bridges JavaScript applications running in ...

  3. 腾讯云-NGINX搭建静态网站

    搭建静态网站 搭建Http静态服务器环境 任务时间:15min ~ 30min 搭建静态网站,首先需要部署环境.下面的步骤,将告诉大家如何在服务器上通过 Nginx 部署 HTTP 静态服务. 00. ...

  4. Android网络开发之WebKet引擎基础

    Android浏览器的内核是Webkit引擎,WebKit的前身是KDE小组的KHTML. Apple公司推出的Safari浏览器,使用的内核是装备了KHTML的WebKit引擎. WebKit内核在 ...

  5. PHP-深入学习Smarty

    本文中的边界标签分别为"<{"和"}>" start-12, 都是静态模板中的内容, 即使函数也只是模板中的标签或者变量调解器; 13-end, 都 ...

  6. HDUOJ------2398Savings Account

    Savings Account Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...

  7. logback+slf4j作为日志系统

    一.logback简介 log4j和logback作者是同一人:CekiGülcü.log4j和logback都是实打实的日志系统. commons-logging,slf4j这两者是日志大管家.sl ...

  8. 为Github 托管项目的访问添加SSH keys

    为了便于访问远程仓库,各个协作者将自己的本地的项目内容推送到远程仓库中,使用 SSH keys 验证github的好处:不用每次提交代码时都输入用户名和密码. 如果SSH key没有添加到github ...

  9. eclipse 在Servers窗口创建一个Tomcat 6.0 Server失败

    web项目部署到tomcat除了用eclipse插件,eclipse也有一个Servers窗口来部署.   问题背景:Servers窗口,我之前创建过一个Tomcat v6.0 Server,后来我把 ...

  10. 细说 ASP.NET控制HTTP缓存[转]

    阅读目录 开始 正常的HTTP请求过程 缓存页的请求过程 缓存页的服务端编程 什么是304应答? 如何编程实现304应答 如何避开HTTP缓存 在上篇博客[细说 ASP.NET Cache 及其高级用 ...