标签:
题目就是:
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