[leetcode] Divide Two Integers

來源:互聯網
上載者:User

標籤:class   blog   code   java   http   tar   

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

https://oj.leetcode.com/problems/divide-two-integers/

思路1:看樣只能用減法了,依次減去除數,TOTS,肯定逾時。

思路2:每次減去N倍的除數,結果也加上N次,因此我們需要將除數擴大N倍。

  1. int擴充成long防止溢出。
  2. multi[i]儲存除數擴大i倍的情況,然後用被除數減。
  3. 負數處理。
public class Solution {    public int divide(int dividend, int divisor) {        if (dividend == 0 || divisor == 1)            return dividend;        long divid = dividend;        long divis = divisor;        boolean neg = false;        int result = 0;        if (dividend < 0) {            neg = !neg;            divid = -divid;        }        if (divisor < 0) {            neg = !neg;            divis = -divis;        }        long[] multi = new long[32];        for (int i = 0; i < 32; i++)            multi[i] = divis << i;        for (int i = 31; i >= 0; i--) {            if (divid >= multi[i]) {                result += 1 << i;                divid -= multi[i];            }        }        return (neg ? -1 : 1) * result;    }    public static void main(String[] args) {        System.out.println(new Solution().divide(5, 2));        System.out.println(new Solution().divide(5, -2));        System.out.println(new Solution().divide(100, 2));        System.out.println(new Solution().divide(222222222, 2));        System.out.println(new Solution().divide(-2147483648, 2));    }}

 

 

參考:

http://blog.csdn.net/doc_sgl/article/details/12841741

http://blog.csdn.net/linhuanmars/article/details/20024907

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.