【JavaScript】网传字节跳动面试题:实现一个32进制的加法
【编程题】实现一个 36 进制的加法 0-9 a-z。
输入 abbbb 1 输出 abbbc
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="text" id="input1" /> <input type="text" id="input2" /> <span id="show"></span> <button onclick="calcu()">计算</button> <script> function calcu() { var num1 = document.getElementById("input1").value; var num2 = document.getElementById("input2").value; var arr1 = num1.split(""); var arr2 = num2.split(""); var result = [] arr1 = arr1.reverse() arr2 = arr2.reverse() // console.log(arr1, arr2) if (arr1.length < arr2.length) { var temp = arr1; arr1 = arr2; arr2 = temp; } var jinwei = 0;// 一开始没有进位 arr1.map((t, i) => { var sum = 0; if (arr2[i]) { sum = getInt(t) + getInt(arr2[i]) + jinwei; } else { sum = getInt(t) + jinwei; jinwei = 0;//从此不再有进位 } result.push(getChar(sum)) }); console.log("结果:" + result.reverse().join()) document.getElementById("show").innerText = result.join(); } // 基于ascii,将十进制整数转化为 36进制字符 function getChar(num) { if (num <= 9) { return String.fromCharCode("0".charCodeAt(0) + num); } else { return String.fromCharCode(num - 10 + "a".charCodeAt(0)); } } // 基于ascii,将36 进制字符转化为 10进制整数 function getInt(char) { if (char.charCodeAt(0) <= "9".charCodeAt(0)) { return char.charCodeAt(0) - "0".charCodeAt(0); } else { return char.charCodeAt(0) - "a".charCodeAt(0) + 10; } } </script> </body> </html>