在JavaScript中,我如何得到:

一个给定整数除另一个整数的整数倍是多少? 其余的呢?


当前回答

我通常使用:

const quotient =  (a - a % b) / b;
const remainder = a % b;

它可能不是最优雅的,但它是有效的。

其他回答

Alex Moore-Niemi的评论作为回答:

对于从谷歌搜索divmod的ruby,你可以这样实现它:

function divmod(x, y) {
  var div = Math.trunc(x/y);
  var rem = x % y;
  return [div, rem];
}

结果:

// [2, 33]

你也可以使用三元来决定如何处理正整数值和负整数值。

var myInt = (y > 0) ? Math.floor(y/x) : Math.floor(y/x) + 1

如果这个数字是正数,就没有问题。如果这个数字是负数,它会加1,因为数学。地板处理否定。

我不是位运算的专家,但这里有另一种方法来获得整个数字:

var num = ~~(a / b);

这也适用于负数,而Math.floor()将以错误的方向舍入。

这似乎也是正确的:

var num = (a / b) >> 0;

我通常使用:

const quotient =  (a - a % b) / b;
const remainder = a % b;

它可能不是最优雅的,但它是有效的。

如果你只是用2的幂除法,你可以使用位运算符:

export function divideBy2(num) {
  return [num >> 1, num & 1];
}

export function divideBy4(num) {
  return [num >> 2, num & 3];
}

export function divideBy8(num) {
  return [num >> 3, num & 7];
}

(第一个是商,第二个是余数)