iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 3
0
自我挑戰組

從零開始學JavaScript系列 第 3

【03】基礎解題練習

  • 分享至 

  • twitterImage
  •  

前言

由於今天找到一個國外線上解題網站,所以決定練習一題,練個手感。


題目

  • For example, if we run 9119 through the function, 811181 will come out, because 9^2 is 81 and 12^2 is 1.

    Note: The function accepts an integer and returns an integer.

  • Sample Tests :

Test.assertEquals(squareDigits(9119), 811181);

解法

function squareDigits(num){
  let str = num.toString(); //將輸入數字轉為字串
  let result = '';
  for(let i = 0;i < str.length;i++){
    let x = parseInt(str.charAt(i),10); //把字串切割為一個一個數字
    let temp = (x * x).toString(); //各自平方後轉回字串
    result += temp;  
  }
  return parseInt(result,10);
}

重點整理

  1. 字串.charAt(index) : 回傳該字串指定位置的單一字串。

    • 如果參數index不在0與字串.length之间,該函式將會回傳空字串。
  2. parseInt(字串)Number(字串)都是將字串轉為數字,但其差別在於 :

    • parseInt(字串)
      如果發現字串中有非數字的單元,將會抓取該單元之前的所有數字,例如
    parseInt("123qwe456"); //回傳123
    
    • Number(字串)
      如果發現字串中有非數字的單元,將會直接回傳NaN,例如 :
    Number("123qwe456"); //回傳NaN
    
  3. 數字.toString()String(數字)都是將數字轉為字串,但其差別在於 :

    • 數字.toString()
      當value為null或者undefined時就無法使用,例如
    null.toString(); 
    //Cannot read property 'toString' of null
    
    undefined.toString(); 
    //Cannot read property 'toString' of undefined
    
    • String(數字)
      當value為null或者undefined時仍可使用,例如 :
    String(null); //回傳"null"
    
    String(undefined); //回傳"undefined"
    

參考與引用來源

  1. https://www.w3school.com.cn/index.html
  2. https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/254123/

上一篇
【02】宣告變數注意重點
下一篇
【04】網頁練習 - 更改背景顏色
系列文
從零開始學JavaScript24
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
harry xie
iT邦研究生 1 級 ‧ 2020-09-06 00:40:18

Codewars 真的是不錯的練題網站,而且還有等級制度區分題目的難度~

我要留言

立即登入留言