lintcode 1665. 计算数字

给出一个十进制数num,现在你需要把它转成二进制数,并返回1的个数和位置。

样例
例1:

输入: 10
输出: [2,1,3]
解释: 10转成2进制为1010,总共有2个1,所以ouptput数组第一个是2。然后1的位置是第1个和第3个,所以后续两个数为1,3.
例2:

输入: 7
输出: [3,1,2,3]
解释: 7转成2进制为111,总共有3个1,所以output数组第一个是3。然后的位置是第1个、第2个和第3个,所以后续三个数为1,2,3.
注意事项
n<=10^9

思路:用string前插记录其二进制数,再通过记录位置依次输出即可

class Solution {
public:
    /**
     * @param num: the num
     * @return: the array subject to the description
     */
    vector<int> calculateNumber(int num) {
        // Write your code here.
        int count=0;
        vector<int> res;
        string tmp;
        res.push_back(count);
        while(num)
        {
            tmp.insert(tmp.begin(),num%2+'0');
            num/=2;
        }
        for (int i = 0; i < tmp.size(); i++) {
            /* code */
            if(tmp[i]-'0') 
            {
                count++;
                res.push_back(i+1);
            }
        } 
        res[0]=count;
        return res;
    }
};
发布了330 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103749088