Give a one-line C expression to test whether a number is a power of 2. [No loops allowed – it’s a simple test.]

我之前的想法好像是 使用LOG去算 就是  lnx / ln2 然後 跟 int( lnx /ln2) 比較看一不一樣

今天看到一個寫法

if (x && !(x & (x-1)) == 0) 但這裡只有假設 x>=0,那位甚麼不乾脆寫

if (x>0 &&!(x & (x-1)) == 0)

This entry was posted in 電腦和網際網路. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s