Skip to content

Instantly share code, notes, and snippets.

@linxinemily
Created March 20, 2019 17:06
Show Gist options
  • Save linxinemily/90ff1561d708edd5999b3e057d309397 to your computer and use it in GitHub Desktop.
Save linxinemily/90ff1561d708edd5999b3e057d309397 to your computer and use it in GitHub Desktop.
var licenseKeyFormatting = function(S, K) {
let str = S.replace(/-/g, "").toUpperCase() //去除"-"並改成大寫
let result = '' //每次迴圈跑完就對這個空字串添加字符
let countK = 0
for(let i =str.length-1; i >= 0; i--) { //由後往前遍歷字串,起始點是最後一個字,終點是第0個字
letter = str[i]
result += letter
countK ++
if(countK == K){ //如果剛好加到第 K 個,就要再加上"-"
result += '-'
countK = 0
}
}
if(result != 0 && result[result.length - 1] == '-') {
result = result.substring(0, result.length-1)
}
return result.split("").reverse().join("")
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment