{ "type": "code_options", "author": "csdn.net", "source": "solution.md", "exercise_id": "04eb6e04293b450d8a2149cd4b65c1a0", "keywords": "位运算,数学", "title": "两数相除", "desc": [ { "content": "\n

给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。

返回被除数 dividend 除以除数 divisor 得到的商。

整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2

 

示例 1:

输入: dividend = 10, divisor = 3
输出:
3
解释:
10/3 = truncate(3.33333..) = truncate(3) = 3

示例 2:

输入: dividend = 7, divisor = -3
输出:
-2
解释:
7/-3 = truncate(-2.33333..) = -2

 

提示:

", "language": "markdown" } ], "answer": [ { "content": "", "language": "java" } ], "prepared": [ [ { "content": "", "language": "java" } ], [ { "content": "", "language": "java" } ], [ { "content": "", "language": "java" } ] ], "template": { "content": "class Solution {\n\tpublic int divide(int dividend, int divisor) {\n\t\tif (dividend == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (dividend == Integer.MIN_VALUE && divisor == -1) {\n\t\t\treturn Integer.MAX_VALUE;\n\t\t}\n\t\tboolean negative;\n\t\tnegative = (dividend ^ divisor) < 0;\n\t\tlong t = Math.abs((long) dividend);\n\t\tlong d = Math.abs((long) divisor);\n\t\tint result = 0;\n\t\tfor (int i = 31; i >= 0; i--) {\n\t\t\tif ((t >> i) >= d) {\n\t\t\t\tresult += 1 << i;\n\t\t\t\tt -= d << i;\n\t\t\t}\n\t\t}\n\t\treturn negative ? -result : result;\n\t}\n}", "language": "java" }, "node_id": "dailycode-38686faac5e447d8b52391e777bd15b5", "license": "csdn.net", "created_at": 1637894158, "topic_link": "https://bbs.csdn.net/topics/600470833" }