xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode 29. Divide Two Integers 题解教程 All In One

LeetCode 29. Divide Two Integers 题解教程 All In One

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

https://leetcode.cn/problems/divide-two-integers

image

// function divide(dividend: number, divisor: number): number {
//  // return ~~(dividend / divisor);
//  let n: number = ~~(dividend / divisor);
//  return n > (2**31 - 1) ? (2**31 - 1) : n;
// };

// function divide(dividend: number, divisor: number): number {
//  // return ~~(dividend / divisor);
//  let n: number = Math.floor(dividend / divisor);
//  return n > (2**31 - 1) ? (2**31 - 1) : n;
// };

function divide(dividend: number, divisor: number): number {
  let temp: number = dividend / divisor;
  let n: number;
  if(temp >= 0) {
    // ✅
    n = Math.floor(temp);
    // ❌ 溢出 bug
    // n = ~~(temp);
  } else {
    // ✅
    // n = Math.ceil(temp);
    // ✅✅
    n = ~~(temp);
  }
  let max = 2**31 - 1;
  return n > max ? max : n;
};

/*

~~(7/-3);
-2

~~(-7/-3);
2

// ❌ 溢出 bug
~~(-2147483648/-1);
-2147483648
~~(-2147483647/-1);
2147483647

*/

/*


 Math.floor(-2147483648/-1);
2147483648
 Math.floor( 7/-3);
-3

(-2147483648/-1);
2147483648
~~(-2147483648/-1);
-2147483648

*/

/*

Wrong Answer
993 / 994 testcases passed

Input
dividend =
-2147483648
divisor =
-1


Output
-2147483648
Expected
2147483647

 */


/*

Testcase

10
3
7
-3
-2147483648
-1

 */

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-03-04 22:38  xgqfrms  阅读(10)  评论(1编辑  收藏  举报