iT邦幫忙

0

【GreatFrontEnd】Count Set Bits in a Binary Number

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20260102/20181142zjQJDxhaoq.png

toString(2) 可以把數字轉成二進位的字串

(9).toString(2) //1001 

數字外要加括號,否則 JS 預設會將.當作小數點,導致語法錯誤

除了二進位外,還有八進位 toString(8)、十六進位 toString(16)、三十六進位 toString(36)
什麼都不寫的 toString() 默認為十進位

因為題目要求 set bits 也就是 1 的數量,因此先把字串轉成陣列後用 filter 留下 1

(9).toString(2).split("").filter(n=>n===1) //["1","1"]

最後 return length 即可

return (9).toString(2).split("").filter(n=>n===1).length //2

題目連結: https://www.greatfrontend.com/questions/algo/count-ones-in-binary


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言