使用JavaScript交换两个数字,我们需要使用第三个变量[关闭]

问题描述 投票:0回答:1

我已经尝试了下面的代码,但仍然有一些测试用例失败,并且出现错误

function swap(num1 , num2){
        
   /* Write your code here
    No need to specify return type 
    Input and output already taken care of, you have to just return the output variable */
    let temp = num1;
    num1 = num2;
    num2 = temp;
    return [num2, num1]

   
    //Return an array of reversed num1 & num2 like {num1 , num2
}
function swap(num1 , num2){
        
   /* Write your code here
    No need to specify return type 
    Input and output already taken care of, you have to just return the output variable */
    let temp = num1;
    num1 = num2;
    num2 = temp;
    return [num2, num1]

   
    //Return an array of reversed num1 & num2 like {num1 , num2
}

尝试过但没有成功

javascript reactjs numbers swap
1个回答
-1
投票

这是一个常见的面试问题,或者至少曾经是。请参阅下面的一种使用算术的实现。

function swap(a, b) {
  a = a + b;
  b = a - b;
  a = a - b;
  return [a, b];
}

console.log(swap(1, 2));

© www.soinside.com 2019 - 2024. All rights reserved.