作者ZooseWu (動物園 公告)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Mon Oct 23 21:19:56 2023
342.Power of Four
檢查數字n是不是4的x次方倍
如果n=4^x則回傳true,否則回傳false
題:1 答:true
題:5 答:false
題:16答:true
Follow up: 不用遞迴或迴圈完成題目
First thought:
一開始就寫了一個迴圈
如果數字比較小 就*4再比一次
不過看到Follow up之後決定想一下最佳解
Approach:
後來看到4這個數字跟2有關
想到可以用binary去解
4的次方倍 換成binary一定是1+偶數個0
例如:
1=1
4=100
16=10000
64=1000000
所以把數字轉成binary後用正規表達式去檢驗就好了
TS code:
function isPowerOfFour (n: number): boolean {
const binary = (n).toString(2)
const reg = /^1(00)*$/
const result = reg.exec(binary)
return result !== null
}
一行版本
function isPowerOfFour (n: number): boolean {
return /^1(00)*$/.exec(n.toString(2)) !== null
}
不過我蠻好奇正規表達式本身的時間複雜度是多少
該不會我寫一個*或+他就會跑迴圈吧?
--
Zoosewu
Yoututbe顯示PTT推文
可以在各個網站追實況或Live時使用
預覽圖:
https://i.imgur.com/ZhtXdAJ.png https://i.imgur.com/WqbLNV3.png
完整介紹:
https://github.com/zoosewu/PTTChatOnYoutube/tree/master/homepage
支援的網站:
Youtube Twitch Holotools Niji-mado Holodex
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.229.33 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1698067199.A.C23.html
推 oin1104: 大師 10/23 21:22
推 sustainer123: 問一下正規表達式那行 1(00)*$ 10/23 21:28
→ sustainer123: 是指1開頭後面0的所有數字嗎? 10/23 21:28
推 AquaCute: 看到解答區有人直接從4^0到4^15查表 笑死 10/23 21:31
→ ZooseWu: 1後面接偶數個0 10/24 01:40