日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

leetcode342合理运用位操作判断4的幂

發布時間:2025/5/22 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode342合理运用位操作判断4的幂 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

我的解法極其垃圾,建議不要看。

public class Solution {public boolean isPowerOfFour(int num) {if(num == 0 || (num != 1 && num % 4 != 0))return false;else if(num == 1 || num == 4)return true;elsereturn isPowerOfFour(num/4);} }

解釋一下高手的解法。

public boolean isPowerOfFour(int num) {return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;//0x55555555 is to get rid of those power of 2 but not power of 4//so that the single 1 bit always appears at the odd position }

要滿足一個數是四的n階指數如16,64這種,上面給出的解法意思就是要滿足三個條件。

1、大于零

2、比它小1的數相與為0,簡單的說,這個數的二進制表示的時候只能有一個1,其他的均為0

3、這個唯一的1必須正確的位置上面,

0x55555555 十六進制數,是01010101010101010101010101010101 和這個數相與如果結果不為那么1就在01010101010101010101010101010101的1的位置上面,只有一個1且還在這些位置上面的數都是滿足條件的。

轉載于:https://www.cnblogs.com/linkstar/p/5926322.html

總結

以上是生活随笔為你收集整理的leetcode342合理运用位操作判断4的幂的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。