`
hcx2013
  • 浏览: 88786 次
社区版块
存档分类
最新评论

Divide Two Integers

 
阅读更多

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

If it is overflow, return MAX_INT.

 

public class Solution {
    public int divide(int dividend, int divisor) {
    	int r = 0;
        if (divisor == 0) {
        	return 0;
        }
        if (dividend == Integer.MIN_VALUE && divisor == Integer.MIN_VALUE) {
        	return 1;
        } else if (divisor == Integer.MIN_VALUE) {
        	return 0;
        } else if (dividend == Integer.MIN_VALUE) {
        	if (divisor == -1) {
        		return Integer.MAX_VALUE;
        	}
        	int res = div(add(dividend, 1), divisor);
        	return add(res, div(minus(dividend, multi(res, divisor)), divisor));
        } else {
        	return div(dividend, divisor);
        }
        
    }

	private int minus(int a, int b) {
		// TODO Auto-generated method stub
		return add(a, negNum(b));
	}

	private int multi(int a, int b) {
		// TODO Auto-generated method stub
		int res = 0;
		while (b != 0) {
			if ((b & 1) != 0) {
				res = add(res, a);
			}
			a <<= 1;
			b >>>= 1;
		}
		return res;
	}

	private int div(int a, int b) {
		// TODO Auto-generated method stub
		int x = isNeg(a) ? negNum(a) : a;
		int y = isNeg(b) ? negNum(b) : b;
		int res = 0;
		for (int i = 31; i > -1; i = minus(i, 1)) {
			if ((x >> i) >= y) {
				res |= (1 << i);
				x = minus(x, y << i);
			}
		}
		return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
	}

	private int negNum(int a) {
		// TODO Auto-generated method stub
		return add(~a, 1);
	}

	private boolean isNeg(int a) {
		// TODO Auto-generated method stub
		return a < 0;
	}

	private int add(int a, int b) {
		// TODO Auto-generated method stub
		int sum = a;
		while (b != 0) {
			sum = a ^ b;
			b = (a & b) << 1;
			a = sum;
		}
		return sum;
	}
}

 

 

public class Solution {
    public int divide(int dividend, int divisor) {
        if (dividend == 0 || divisor == 0) {  
            return 0;  
        }  
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
        	return Integer.MAX_VALUE;
        }
        boolean isNeg = (dividend > 0 && divisor < 0)  
                || (dividend < 0 && divisor > 0);  
        long a = Math.abs((long) dividend);  
        long b = Math.abs((long) divisor);  
        if (b > a) {  
            return 0;  
        }  
  
        long sum = 0;  
        long pow = 0;  
        int result = 0;  
        while (a >= b) {  
            pow = 1;  
            sum = b;  
            while (sum + sum <= a) {  
                sum += sum;  
                pow += pow;  
            }  
            a -= sum;  
            result += pow;  
        }  
        return isNeg ? -result : result;  
    }
}

 

0
0
分享到:
评论

相关推荐

    c语言-leetcode 0029-divide-two-integers.zip

    c c语言_leetcode 0029_divide_two_integers.zip

    js-leetcode题解之29-divide-two-integers.js

    js js_leetcode题解之29-divide-two-integers.js

    leetcode叫数-python01:Python01

    先来看LeetCode-29上的Divide Two Integers题目要求: Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. 1 2 3 就是说不用乘法,除法,求模运算...

    _leetcode-python.pdf

    - Divide Two Integers: 实现整数除法,不能使用乘法、除法和模运算符。 - Search in Rotated Sorted Array: 在旋转过的排序数组中进行二分查找。 - Search for a Range: 给定一个按照升序排列的数组,和一个目标值...

    lovely-nuts:这是一个可爱的坚果

    Practice-Leetcode 这是一个Chinese School Girl:China:用来练习leetcode的文档....29.Divide Two Integers 二进制累加代替除法,防止溢出 36.Valid Sudoku set去重复 2018/04/19: 038.Count and Say 递归 040.C

    LeetCode最全代码

    371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | ...

    丢失的最小正整数leetcode-interview-algorithm:面试时的JS算法

    Divide Two Integers 两个整数相除,要求不能使用 *,/,以及mod操作符,返回除数,若除数有小数点,只返回整数部分,如2.789,只应返回2,此题为leetcode上的题目 Random Numbers 用计算机生成了N个1到1000之间的...

    leetcodepalindrom-solutions_to_problems:解决问题的解决方案

    5. **除以两个整数(Divide Two Integers)** 任务是实现一个函数,模拟整数除法,返回商(不考虑浮点数部分)。这个题目需要考虑整数溢出问题,可以使用位运算和减法进行求解。例如,将除数和被除数都乘以一个足够大...

    Dir-For-LeetCode

    问题 完全的 017_Letter_Combinations_of_a_Phone_Number 018_4总和 019_Remove_Nth_Node_From_End_of_List 020_Valid_Parentheses ... 029_Divide_Two_Integers 030_Substring_with_Concatenation_of

    HugeInteger大整数计数器作业

    HugeInteger Class) Create a class HugeInteger that uses a 40-element array of digits to store integers as large as 40 digits each. Provide member functions input, output, add and subtract. For ...

    一个关于加减乘除的程序

    printf("Enter two integers: "); if (scanf("%d %d", &a, &b) == 2) { // 检查是否成功读取两个整数 printf("a=%d\nb=%d\n", a, b); printf("a+b=%d\n", a + b); if (b != 0) { printf("a/b=%d\n", a / b); } ...

    leetcode切割分组-leetcode:leetcode

    029_divide_two_integers*.py # 实现整除 050_pow.py # 实现乘幂 066_plus_one.py # 数列末尾值+1 069_sqrt.py # 实现开根号 136_single_number.py # 位操作:异或(xor)操作 x ^ 0 = x; x ^ x = 0 sum 001_two_sum....

    复杂度测试 Performance Measurement

    The recursive method is to equally divide the integer set into two parts by the integer in the middle position. Then recursively print the first part, followed by printing the integer in the middle, ...

    计算机组成与结构体系英文课件:Chapter9 Arithmetic.pdf

    3. **Unsigned Two's Complement Representation**: This method allows representation of both positive and negative integers. Positive numbers and zero are represented identically to their unsigned ...

    leetcode1-240题中文题解,md格式,java

    8. leetcode-29-Divide-Two-Integers.md:第29题,两数相除,涉及到整数除法和位运算。 9. leetcode-218-The-Skyline-Problem.md:第218题,天际线问题,可能涉及到二维数组处理和线段树或平衡二叉搜索树的数据结构...

    Microsoft Library MSDN4DOS.zip

    Chapter 4 Defining and Using Integers Chapter 5 Defining and Using Complex Data Types Chapter 6 Using Floating-Point and Binary Coded Decimal Numbers Chapter 7 Controlling Program Flow Chapter 8 ...

    python中使用input()函数获取用户输入值方式

    numbers_str = input("Enter two non-zero integers separated by comma: ") nums = [int(n) for n in numbers_str.split(",")] result = calculate(nums[0], nums[1]) print(result) ``` 在这个函数中,我们首先将...

    Go 学习笔记 第四版

    func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } ``` - **匿名函数**:可以在任何地方定义匿名函数,并可以将其作为值传递给其他函数。...

    语言程序设计课后习题答案

    第 一 章 概述 1-1 简述计算机程序设计语言的发展历程。 解: 迄今为止计算机程序设计语言的发展经历了机器语言、汇编语言、高级语言等阶段,C++语言是一种面向对象的编程语言,也属于高级语言。...

Global site tag (gtag.js) - Google Analytics