[leetcode]题型整理之用bit统计个数
137. Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int x = 0x40000000;
//find the first binary from where m is different from n
int i = 1;
for(i = 1; i < 32; i++){
int a = m & x;
int b = n & x;
if(a != b){
break;
}
x = x >> 1;
}
i--;
//i is the last binary where m is the same as n
int y = 0x80000000;
y = y >> i;
int result = m & y;
return result;
}
}
九章的代码更短
268. Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
public class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int sum = nums[0];
for (int i = 1; i < n; i++) {
sum = sum ^ nums[i];
}
int sum2 = 0;
for (int i = 1; i <= n; i++) {
sum = sum ^ i;
}
return sum2 ^ sum;
}
}
how to decide if a number is power of 2?
(num&-num) == num
最新文章
- sql select 1-10的数字
- vtkQuadric创建二次曲面
- 利用yeoman快速搭建React+webpack+es6脚手架
- C#多线程网摘 1
- shellKali Linux Web 渗透测试— 初级教程(第三课)
- esp和ebp详解
- px,em,rem的区别
- Shell编程学习---第五篇:Shell的输入和输出
- java1.8的几大新特性(二)
- UITableView.m:8042 crash 崩溃
- iOS 获取通讯录里边的电话号码AddressBook
- sqlplus 链接数据库
- wireshark的 rdp dissector
- DIV+CSS规范命名
- Oracle删除死锁进程的方法
- Zookeeper动态更新服务器列表
- 怎么正确的回滚git的代码?
- 第三个sprint冲刺第三阶段
- MT【209】打破对称
- 理解Java枚举类型
热门文章
- Bubble Cup 8 finals A. Fibonotci (575A)
- java使double保留两位小数的多方法 java保留两位小数
- Error configuring application listener of class。。。NoClassDefFoundError。。某Listener 之启动tomcat报错
- linux 远程连接工具——MTPuTTY
- 【01-05】hibernate BaseDao
- leetcode--Different Ways to Add Parentheses
- SQL语句生成指定范围内随机数
- 成功开发iPhone软件的10个步骤
- knn-伪代码与实现过程
- BugFree 测试管理系统