LeetCode 1: Number of 1 Bits (C++)
来源:互联网 发布:雅马哈p115软件 编辑:程序博客网 时间:2024/06/05 01:57
代码格式:
•LeetCode不允许自己定义函数,只需要实现给定的函数即可。
•不需要定义main()函数,否则会编译通不过。
•如果需要有输出,直接return就行。我在第一题中使用了cout,就通不过。
题目描述:
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as theHamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
解题思路:
本题就是求一个无符号整数中1的个数,首先想到的是直接数,我的第一思路就是如此。还有一种方法就是使用技巧:n&(n-1)。
解法1:计数整数中的1。
#include<iostream>using namespace std;class Solution{ public: int hammingWeight(uint32_t n) { int count=0; for(int i=0;i<32;i++) { if (n&(1<<i)) coun0t++;//如果出现1就给计数器加一 } return count; }};
解法二:n&(n-1)可以将n的二进制表示的末尾1变成0,如果n末尾是0,则仍然是0.
class Solution {public: int hammingWeight(uint32_t n) { int count=0; while(n)//如果n的末尾(至少是末尾)有1则将其去掉,并计数。 { n&=n-1; count++; } return count; }};
另外:n&-n可以保留末尾的0
0 0
- LeetCode 1: Number of 1 Bits (C++)
- 【LeetCode-191】 Number of 1 Bits(C++)
- leetcode:bits:Number of 1 Bits(191)
- LeetCode:Number of 1 Bits
- LeetCode-Number of 1 Bits
- leetcode: Number of 1 Bits
- LeetCode Number of 1 Bits
- Leetcode: Number of 1 Bits
- Leetcode--Number of 1 Bits
- [LeetCode] Number of 1 Bits
- [leetcode]Number of 1 Bits
- Leetcode-Number of 1 Bits
- LeetCode Number of 1 Bits
- LeetCode-Number of 1 Bits
- [Leetcode] Number of 1 Bits
- [Leetcode]Number of 1 Bits
- leetcode--Number of 1 Bits
- leetcode:Number of 1 Bits
- JAVA的可变类与不可变类
- 第五届河南省程序设计大赛
- Java图片上传压缩处理
- BZOJ1018
- CDUESTC 2016 假期赛1 B题
- LeetCode 1: Number of 1 Bits (C++)
- BZOJ1074: [SCOI2007]折纸origami
- Oozie4.2.0配置安装实战
- QGis二次开发基础 -- 栅格图像增强显示
- wrapper打包java程序
- OpenFlow笔记
- UltimateRecyclerView的使用方法详解
- ThinkPHP的静态缓存,非系统写法。
- Android TextView借助Linkify,使用自定义模式设置链接