马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Python 24 ms :
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return bin(n).count("1") == 1 if n >= 1 else False
C++ 0 ms :
// https://leetcode-cn.com/problems/power-of-two/submissions/
#include <string>
using namespace std;
string int2str(int n);
string reverse(string s);
string dec2bin(int n)
{
string res = "";
while (n)
{
res += int2str(n % 2);
n /= 2;
}
res = reverse(res);
return res;
}
string int2str(int n)
{
int m = n;
char s[100];
char ss[100];
int i = 0, j = 0;
if (n < 0)
{
m = 0 - m;
j = 1;
ss[0] = '-';
}
while (m > 0)
{
s[i++] = m % 10 + '0';
m /= 10;
}
s[i] = '\0';
i = i - 1;
while (i >= 0)
{
ss[j++] = s[i--];
}
ss[j] = '\0';
string res = ss;
return res;
}
string reverse(string s)
{
int i;
string a = "";
for (i = s.size() - 1; i >= 0; i--)
a += s[i];
return a;
}
int count(string str, char ch)
{
int i, r = 0;
for (i = 0; i < str.size(); i++)
{
if (str[i] == ch)
{
r++;
}
}
return r;
}
class Solution
{
public:
bool isPowerOfTwo(int n)
{
if (n < 1)
return false;
return count(dec2bin(n), '1') == 1;
}
};
JavaScript 80 ms :
function reverse(string) {
var a = "";
for (var i = string.length - 1; i >= 0; i--) {
a += string[i];
}
return a;
}
function count(string, char) {
var r = 0;
for (var i = 0; i < string.length; i++) {
if (string[i] == char) r++;
}
return r;
}
function dec2bin(n) {
var res = "";
while (n) {
res += (n % 2).toString();
n -= (n % 2);
n /= 2;
}
return reverse(res);
}
function isPowerOfTwo(n) {
if (n < 1) return false;
else if (n == 1 || n == 2) return true;
return count(dec2bin(n), "1") == 1;
}
|