剑指刷题——运算符
文章目录
- 剑指刷题——运算符
- [剑指 Offer 15. 二进制中1的个数](https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/)
- [剑指 Offer 56 - I. 数组中数字出现的次数](https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/)
- [剑指 Offer 65. 不用加减乘除做加法](https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/)
剑指 Offer 15. 二进制中1的个数
难度简单
请实现一个函数,输入一个整数(以二进制串形式),输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
提示:
- 输入必须是长度为
32
的 二进制串 。
注意:本题与主站 191 题相同:https://leetcode-cn.com/problems/number-of-1-bits/
//逐位判断
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n!=0){
count+=n&1;
n>>>=1;
}
return count;
}
}
//巧用 n \& (n - 1)n&(n−1)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res =0 ;
while(n!=0){
res++;
n&=(n-1);
}
return res;
}
}
剑指 Offer 56 - I. 数组中数字出现的次数
难度中等
一个整型数组 nums
里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]
限制:
2 <= nums.length <= 10000
class Solution {
public int[] singleNumbers(int[] nums) {
int n= nums[0];
for (int i = 1; i < nums.length; i++) {
n^=nums[i];
}
int k = 1;
while((k&n) == 0){
k<<=1;
}
int a= 0;
int b= 0;
for (int i = 0; i < nums.length; i++) {
if((k&nums[i])==0){
a^=nums[i];
}else{
b^=nums[i];
}
}
return new int[]{a,b};
}
}
剑指 Offer 65. 不用加减乘除做加法
难度简单
写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。
示例:
输入: a = 1, b = 1
输出: 2
提示:
a
,b
均可能是负数或 0- 结果不会溢出 32 位整数
class Solution {
public int add(int a, int b) {
int c= 0;
while(b !=0 ){
c = (a&b)<<1; //进位
a = a^b; //非进位
b = c;
}
return a;
}
}