LeetCode 1: Number of 1 Bits (C++)
2016-01-23 17:17
417 查看
代码格式:
•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。
解法二:n&(n-1)可以将n的二进制表示的末尾1变成0,如果n末尾是0,则仍然是0.
另外:n&-n可以保留末尾的0
•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
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解