javascript - 如何在 JavaScript "without using ` +` or ` -` operators"中添加两个数字?

标签 javascript algorithm

我知道使用 + 的替代方法添加符号是做这样的事情:

int add(int a, int b)
{
     if(b == 0)
         return sum;
     sum = a ^ b;
     carry = (a & b) << 1;
     return add(sum,carry);
}

但是我有两个问题:

  • 这是 C++,不是 JavaScript。这在 JavaScript 中受支持吗?
  • 很明显整个技巧都在 ^& << ,但我不知道如何开始在 JavaScript 中查找它们,因为我不知道它们叫什么。 我什至应该用谷歌搜索什么?

我试着用 JavaScript 写这个......但似乎我错过了什么

var getSum = function(a, b) {
  return (a ^ b, (a & b) << 1)
};

最佳答案

我们将使用 bitwise operators并将使用 recursion .

当我们有一些低资源时,我们使用这种方法。 Read more about when to use this method!

var getSum = function(a, b) {
    if (b == 0) {
        return a;
    } else {
        return getSum(a ^ b, (a & b) << 1)
    }
};

@PatrickRoberts 建议的 ECMAScript 6 单行解决方案:

const getSum = (a,b) => b ? getSum(a ^ b, (a & b) << 1) : a;

另一种解决方案:

2- 阵列技术 Array.prototype.fill()

const getSum = (a, b) => {
  const firstArr = new Array(a).fill(true);
  const secondArr = new Array(b).fill(true);
  return firstArr.concat(secondArr).length
}

3- use 的解决方法加号 without writing it :

const getSum = (a, b) => eval(''.concat(a).concat(String.fromCharCode(0x2B)).concat(b));

关于javascript - 如何在 JavaScript "without using ` +` or ` -` operators"中添加两个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41455750/

相关文章:

javascript - 添加 Font Awesome 图标

c++ - 必须首先打印vector <int> v1中最接近整数x的数字

python - 尝试使用 python 计算斐波那契数的最后一位时出现错误 "RuntimeWarning: overflow encountered in long_scalars"

php - PHP中特定计数的非重复组合

javascript - 当谷歌地图标记共享相同的像素时,集群它们

javascript - 通过javascript调用必填字段验证器

javascript - 鼠标悬停时如何在侧边栏上显示子菜单栏?

javascript - 无法将值绑定(bind)到 setter 中 p-autocomplete 中的 ngModel

algorithm - 避免排列模式 - 在没有 231 方案的情况下打印所有排列

algorithm - 高斯分布+哈希表