題目
請輸出1到400之間所有數字中包含的1的個數,比如數字1中包含了一個1, 數字11中包含了兩個1,數字20中不包含1,數字1到21中共包含了13個1,
function getCount() {
}
// 輸出 180
console.log(getCount())
答案
答案一
這個答案比較經典,性能也算是很不錯的了
const sum1s = num => {
let numstr
if (!num) return 0
if (typeof num === 'string') numstr = num
else numstr = String(num)
if (Number(numstr) === 0) return 0
const curr =
numstr[0] > 1
? 10 ** (numstr.length - 1) +
numstr[0] * (numstr.length - 1) * 10 ** (numstr.length - 2)
: sum1s(10 ** (numstr.length - 1) - 1) + 1
return curr + sum1s(numstr.substr(1))
}
// 輸出 180
console.log(sum1s(400))
答案二
這個用到了正則,不過對于長字串正則可能性能會有點點差
function countOne(num){
// num為正整數,方法有點兒暴力
return Array.from({length:num},(v,i)=>i+1).join('').replace(/[^1]/g,'').length
}
console.log(countOne(400))
答案三
下面這個答案算是中規中矩的答案了,將每一個數字轉換為字串然后統計1的個數
function getCount() {
let count = 0
for(let i=1;i<400;i++) {
count = count + `${i}`.split('1').length - 1
}
return count
}
// 輸出 180
console.log(getCount())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/112549.html
標籤:其他
上一篇:微信小程式 - 點餐界面添加購物車左右擺動影片(用戶點擊添加到購物車后會有一個左右擺動的購物車提示)
下一篇:作業三年的前端開發20k簡歷標準
