LeetCode 习题 231. 2 的幂
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;
char ss;
int i = 0, j = 0;
if (n < 0)
{
m = 0 - m;
j = 1;
ss = '-';
}
while (m > 0)
{
s = m % 10 + '0';
m /= 10;
}
s = '\0';
i = i - 1;
while (i >= 0)
{
ss = s;
}
ss = '\0';
string res = ss;
return res;
}
string reverse(string s)
{
int i;
string a = "";
for (i = s.size() - 1; i >= 0; i--)
a += s;
return a;
}
int count(string str, char ch)
{
int i, r = 0;
for (i = 0; i < str.size(); i++)
{
if (str == 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;
}
return a;
}
function count(string, char) {
var r = 0;
for (var i = 0; i < string.length; i++) {
if (string == 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;
} 0ms 是什么鬼
页:
[1]