My cpp solution, easy to understand


  • 0
    W

    int getEven(string& bitEven, int bitCount) {
    string::reverse_iterator iter = bitEven.rbegin();
    ++iter; //1000 + 10 = 1010
    if (*iter == '0') {
    *iter = '1';
    return bitCount+1;
    }

    	for (iter; iter!=bitEven.rend(); ++iter)
    	{
    		if (*iter == '1') {
    			*iter = '0';
    			bitCount --;
    		}
    		else if (*iter == '0') {
    			*iter = '1';
    			bitCount ++;
    			return bitCount;
    		}
    	}
    	const char* onebit = "1";
    	bitEven.insert(0, onebit);
    	return bitCount+1;
    }
    
    vector<int> countBits(int num) {
        vector<int> result;
    	string bitEven;
    	for (int i=0; i<=num; i++) {
    		if (i%2==0) { //偶数
    			if (i==0) {
    				bitEven = "0";
    				result.push_back(0);
    			} else if (i==2) {
    				bitEven = "10";
    				result.push_back(1);
    			}else {
    				result.push_back(getEven(bitEven, result[i-2]));
    			}
    
    		} else { //奇数
    			result.push_back(result[i-1] + 1);
    		}
    
    	}
    	return result;
    }

Log in to reply
 

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