码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 191:number of one bits

时间:2015-03-14 23:05:28      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:

题目就是:

Write a function that takes an unsigned integer and returns the number of ’1‘ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011, so the function should return 3.

这就是考十进制转二进制的题,学到了#include <cstdin>这个头文件,还有简单的转换算法,算法里边数据类型,别随手定义成了int!!!

class Solution {
public:
    int hammingWeight(uint32_t n) 
    {
        uint32_t iRet = 0;
        uint32_t flag = 1;
        uint32_t iRes = n;
        uint32_t iLeft = 0;
        while(flag != 0)
        {
            flag = iRes / 2;
            iLeft = iRes - flag * 2;
            if(iLeft == 1)
            {
                ++iRet;
            }
            iRes = flag;
        }
        return iRet;
    }
};

写的不好,但多code多学习总是有用。

LeetCode 191:number of one bits

标签:

原文地址:http://www.cnblogs.com/bestwangjie/p/4338353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!