Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (動物園 公告)時間2年前 (2023/10/23 21:19), 編輯推噓3(302)
留言5則, 4人參與, 2年前最新討論串456/719 (看更多)
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

10/23 21:22, 2年前 , 1F
大師
10/23 21:22, 1F

10/23 21:28, 2年前 , 2F
問一下正規表達式那行 1(00)*$
10/23 21:28, 2F

10/23 21:28, 2年前 , 3F
是指1開頭後面0的所有數字嗎?
10/23 21:28, 3F

10/23 21:31, 2年前 , 4F
看到解答區有人直接從4^0到4^15查表 笑死
10/23 21:31, 4F

10/24 01:40, 2年前 , 5F
1後面接偶數個0
10/24 01:40, 5F
文章代碼(AID): #1bDdB_mZ (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bDdB_mZ (Marginalman)