反转数字的递归函数

我尝试使用递归函数来反转它有效的数字,但对于一个调用来说,我猜只是因为作用域,但我不知道如何修复它


let num;

let reversed='';

let result; 


function reverseNum(n){ 

 

  for(let i =0; i<n; i++){  

    num = n%10; // get the last digit e.g 352 %10 = 2

    reversed+= num

    result = parseInt(n / 10); // remove last digit e.g. parseInt(352/10) = 35

    reverseNum(result);

    if(result ===0){ 

        break;

    } 

  }

  return reversed;

}


萧十郎
浏览 124回答 1
1回答

潇潇雨雨

每次从外部调用函数时,您都需要重新创建num、reversed和变量。result这是一个简单的调整,通过在 top 函数中定义递归函数reverseNum:function reverseNum(n) {&nbsp; let num;&nbsp; let reversed = '';&nbsp; let result;&nbsp; const recurse = (n) => {&nbsp; &nbsp; for (let i = 0; i < n; i++) {&nbsp; &nbsp; &nbsp; num = n % 10; // get the last digit e.g 352 %10 = 2&nbsp; &nbsp; &nbsp; reversed += num&nbsp; &nbsp; &nbsp; result = parseInt(n / 10); // remove last digit e.g. parseInt(352/10) = 35&nbsp; &nbsp; &nbsp; recurse(result);&nbsp; &nbsp; &nbsp; if (result === 0) {&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return reversed;&nbsp; };&nbsp; return recurse(n);}console.log(reverseNum(1234));console.log(reverseNum(1234));但更优雅的方法是:function reverseNum(n, str = String(n)) {&nbsp; const thisDigit = str[str.length - 1];&nbsp; const recursiveResult = str.length === 1 ? '' : reverseNum(str.slice(0, str.length - 1));&nbsp; return Number(thisDigit + recursiveResult);}console.log(reverseNum(1234));console.log(reverseNum(1234));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript