【问题标题】:How do I Subtract two numbers without using minus operator in JavaScript? Or Using For loop如何在不使用 JavaScript 中的减号运算符的情况下减去两个数字?或使用 For 循环
【发布时间】:2018-09-29 05:04:14
【问题描述】:

Javascript 没有使用位运算符 ??这是我的代码javascript代码

function subtract()
{
    var n1 = parseInt(document.getElementById('fvalue').value);
    var n2 = parseInt(document.getElementById('svalue').value);
    var x1, x2;

    while(n2 != 0)
    {
        var brw = (~n2)&n2;
        n1= n1^n2;
        n2 = brw<<1;
    }

    document.write("Result is : " + n1);
}

【问题讨论】:

    标签: javascript subtraction


    【解决方案1】:

    这是在 javascript 中加减 2 个数字的简单示例:

    console.log(add(2,4));
    console.log(subtract(5,4));
    
    function add( a, b)
    {
       var x;
      x = a^b;
    
      while(a&b)
      {
        b = ((a&b)<<1);
        a = x;
        x = a^b;
        //b=(a^b);
      }
    
      return x;
    }
    function subtract( x,  y) 
    { 
        if (y == 0) 
            return x; 
        return subtract(x ^ y, (~x & y) << 1); 
    } 

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2011-01-04
      • 2021-12-03
      • 2021-12-03
      相关资源
      最近更新 更多