Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
1 | class Solution { |
Reverse Linked List
反转链表
1 | class Solution { |
Number of 1 Bits
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.
解法一(按位判断)
1 | int hammingWeight(uint32_t n) |
解法二
每当n&(n-1)一次,n就会少一位1(最后一位1没了)
1 | class Solution { |
Power of Two
Given an integer, write a function to determine if it is a power of two.
如果n是2的指数,则n的二进制表达中只有一个1,可以通过上题解决
1 | class Solution { |
Power of Three
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
如果不是3的指数,则求出的幂指数不为整数,如12,求出的幂指数为2.26186,则 2.26186-int(2.26186)不为0;
1 | class Solution { |
判断浮点数的大小关系时,首先要判断他们是否相等,不相等再判断大小关系。例如A>B,不一定就是A大于B,有可能他们相等。
1 | int dequals(double a, double b) |