One change in s[j]+= to s[j]=s[j]+... failed the solution


  • 0
    L
    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int s[32]={0};
            for (int i=0; i<n; i++) {
                for (int j=0; j<32; j++) {
                    s[j]+=(A[i]&(1<<j))?1:0;
                }
            }
            int tmp=0;
            for (int j=0; j<32; j++) {
                tmp=tmp|((s[j]%3)<<j);
            }
            return tmp;
        }
    };
    

    The first solution passed

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int s[32]={0};
            for (int i=0; i<n; i++) {
                for (int j=0; j<32; j++) {
                    s[j]=s[j]+(A[i]&(1<<j))?1:0;
                }
            }
            int tmp=0;
            for (int j=0; j<32; j++) {
                tmp=tmp|((s[j]%3)<<j);
            }
            return tmp;
        }
    };
    

    The second solution failed.
    only difference is s[j]+= or s[j]=s[j]+....
    I don't understand why. Can anyone explain this?
    thanks


  • 0
    D

    It because the expression : a + b?1:0 will be treated as (a+b)?1:0;

    so in order to use the second code u need to change to s[j]=s[j]+((A[i]&(1<<j))?1:0);


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.