位1的个数
1.左移一位 n <<= 1; 右移一位 n>>= 1;
2.右移相当于除2!!!!我一开始写除10!!,怪不得算不对我日了
3.n&1的意思是,n与1按二进制位一个一个相&, 可以简单理解为,取出n的二进制中的每一位(从后往前)
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while(n != 0) {
//int temp = n % 10;
if(n & 1) cnt++;
n >>= 2; // n = n / 2;
}
return cnt;
}
};
汉明距离
class Solution {
public:
int hammingDistance(int x, int y) {
int cnt = 0;
while(x != 0 && y != 0) {
int a = x % 2;
int b = y % 2;
if(a != b) cnt++;
x = x / 2;
y = y / 2;
}
//统计位1的个数
while(x != 0) {
if(x & 1) cnt++;
x >>= 1;
}
while(y != 0) {
if(y & 1) cnt++;
y >>= 1;
}
return cnt;
}
};
颠倒的二进制位
关键思想: 对于原整型数的二进制数,逆转其二进制数,相当于取出的第i位,左移32-i位,由于是从0开始的,所以一开始左移数定位在31。
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ans = 0, power = 31;
while (n != 0) {
ans += (n & 1) << power;
n = n >> 1;
power -= 1;
}
return ans;
}
};
有效的括号
看到括号匹配问题直接想栈就完事儿了 注意两个细节
1.string一开始就为空的话,return true;
2.每次遇到右括号,都要判断两件事,第一是栈是否为空,为空就直接false。第二是前面的左括号是不是匹配的,不是就直接false
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
if(s.size()==0) return true;
for(int i=0;i<s.size();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
stk.push(s[i]);
}
else if(s[i]==')')
{
if(stk.empty()) return false;
else if(stk.top()=='(')
{
stk.pop();
}
else return false;
}
else if(s[i]==']')
{
if(stk.empty()) return false;
else if(stk.top()=='[')
{
stk.pop();
}
else return false;
}
else if(s[i]=='}')
{
if(stk.empty()) return false;
else if(stk.top()=='{')
{
stk.pop();
}
else return false;
}
}
if(stk.empty()) return true;
else return false;
}
};
缺失的数字
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int hash[n + 10];
memset(hash, 0, sizeof(hash));
for(int i = 0; i < n; ++i) {
hash[nums[i]]++;
}
int i;
for(i = 0; i < n + 10; ++i) {
if(hash[i] == 0) break;
}
return i;
}
};
杨辉三角
vector<int>(size, value);创建一个vector,元素个数为nSize,且值均为value。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int> > ans;
for(int i = 0; i < numRows; ++i) {
ans.push_back(vector<int>(i + 1, 1)); //第i行有i+1个1
}
for(int i = 0; i < numRows; ++i) {
for(int j = 1; j < i; ++j) {
ans[i][j] = ans[i-1][j-1] + ans[i-1][j];
}
}
return ans;
}
};