leetcode- daily punch -day 5

leetcode daily punch

Attach kuangbin Gangster words motivate yourself:
who me a hundred, ten people I million, or chasing the dream of youth, with confidence of heart, never give up!
2020.2.12


Record their own ideas do have problems, not necessarily the optimal solution

461. Hamming distance

解法一:
class Solution {
public:
    int hammingDistance(int x, int y) {
        int ans = 0;
        while(x > 0 || y > 0)
        {
            if((x & 1) ^ (y & 1))ans++;
            x = x >> 1;y =  y >> 1;
        }
        return ans;
    }
};

解法二
class Solution {
public:
    int hammingDistance(int x, int y) {
        int a = x ^ y , sum = 0;
        while(a)
        {
            sum += a & 1;
            a = a >> 1;
        }
        return sum;
    }
};

1342. The number of operations into a digital 0

class Solution {
public:
    int numberOfSteps (int num) {
        int ans = 0;
        while(num)
        {
            ans++;
            if(num % 2 == 0)num = num >> 1;
            else num -= 1;
        }
        return ans;
    }
};

1290. binary integer transfer list

class Solution {
public:
    int getDecimalValue(ListNode* head) {
        string s;
        while(head)
        {
            if(head->val == 0)s += "0";
            else s+="1";
            head = head->next;
        }
        int ans = 0 ,k = 1;
        for(int i = s.size() - 1;i >= 0; i--)
        {
            if(s[i] == '1')ans += k;
            k *= 2;
        }
        return ans;
    }
};

Guess you like

Origin www.cnblogs.com/wlw-x/p/12301093.html