Solution 1:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isPowerOfTwo(int n) { | |
double num = log2(n); | |
return n==0? false:num==round(num); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isPowerOfTwo(int n) { | |
return n > 0 && !(n&(n-1)); | |
} | |
}; |
Round 2 solution: Need to take care negtive number and zero:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isPowerOfTwo(int n) { | |
if(n<=0) | |
return false; | |
return (n&(n-1))==0; | |
} | |
}; |
No comments:
Post a Comment