标签:problem 代码 判断 problems 题目 类型 boolean font 链接
package leetcode_50; /*** * * @author pengfei_zheng * 不使用乘法、除法、求模实现除法运算 */ public class Solution29 { public int divide(int dividend, int divisor) { long result = divideLong(dividend, divisor); return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)result; } // It‘s easy to handle edge cases when // operate with long numbers rather than int public long divideLong(long dividend, long divisor) { // Remember the sign boolean negative = dividend < 0 != divisor < 0; // Make dividend and divisor unsign if (dividend < 0) dividend = -dividend; if (divisor < 0) divisor = -divisor; // Return if nothing to divide if (dividend < divisor) return 0; // Sum divisor 2, 4, 8, 16, 32 .... times long sum = divisor; long divide = 1; while ((sum+sum) <= dividend) { sum += sum; divide += divide; } // Make a recursive call for (devided-sum) and add it to the result return negative ? -(divide + divideLong((dividend-sum), divisor)) : (divide + divideLong((dividend-sum), divisor)); } }
LeetCode 29 Divide Two Integers (不使用乘法,除法,求模计算两个数的除法)
标签:problem 代码 判断 problems 题目 类型 boolean font 链接
原文地址:http://www.cnblogs.com/zpfbuaa/p/6531700.html