leetcode-每日打卡-day 8
leetcode 每日打卡
those times when you get up early and you work hard; those times when you stay up late and you work hard; those times when don’t feel like working — you’re too tired, you don’t want to push yourself — but you do it anyway. That is actually the dream. That’s the dream. It’s not the destination, it’s the journey. And if you guys can understand that, what you’ll see happen is that you won’t accomplish your dreams, your dreams won’t come true, something greater will. mamba out
那些你早出晚归付出的刻苦努力,你不想训练,当你觉的太累了但还是要咬牙坚持的时候,那就是在追逐梦想,不要在意终点有什么,要享受路途的过程,或许你不能成就梦想,但一定会有更伟大的事情随之而来。 mamba out~
2020.2.17
记录下来自己做题时得思路,并不一定是最优解
371. 两整数之和
class Solution {
public:
int getSum(int a, int b) {
while(b){
// 将要进位的位置记录下来
auto c = ((unsigned int)a & b) << 1 ;
/*
与运算实际上是不进位的加法
*/
a = a ^ b;
b = c; //再将该进位的位置重新进行运算
}
return a;
}
};
// lc上某大佬的讲解
int getSum(int a, int b)
{
int sum, carry;
sum = a ^ b; //异或这里可看做是相加但是不显现进位,比如5 ^ 3
/*0 1 0 1
0 0 1 1
------------
0 1 1 0
上面的如果看成传统的加法,不就是1+1=2,进1得0,但是这里没有显示进位出来,仅是相加,0+1或者是1+0都不用进位*/
carry = (a & b) << 1;
//相与为了让进位显现出来,比如5 & 3
/* 0 1 0 1
0 0 1 1
------------
0 0 0 1
上面的最低位1和1相与得1,而在二进制加法中,这里1+1也应该是要进位的,所以刚好吻合,但是这个进位1应该要再往前一位,所以左移一位*/
if(carry != 0) //经过上面这两步,如果进位不等于0,那么就是说还要把进位给加上去,所以用了尾递归,一直递归到进位是0。
{
return getSum(sum, carry);
}
return sum;
}
190. 颠倒二进制位
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ans = 0;
int i = 32;
while(i--)
{
ans <<= 1;
ans += n & 1;
n >>= 1;
}
return ans;
}
};