首尾數字差異 - JavaScript


我們需要編寫一個 JavaScript 函式,它接收一個數字,從該數字的首尾數字構建一個新數字,並返回原數字和新數字之間的差值。

例如:如果輸入為 34567

那麼首尾數字數將為 -

37

而輸出將為 -

34530

示例

以下是程式碼 -

const num = 34567;
const cornerDifference = num => {
   let temp = Math.abs(num);
   let corner = temp % 10;
   if(temp < 100){
      corner = temp;
   }else{
      while(temp >= 10){
         temp = Math.floor(temp / 10);
      };
      corner = (temp*10) + corner;
   };
   return num - corner;
};
console.log(cornerDifference(num));

輸出

在控制檯中顯示以下輸出 -

34530

更新於: 15-9-2020

96 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.