博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
位运算解决找不同数字、2的幂、1的个数等
阅读量:3941 次
发布时间:2019-05-24

本文共 969 字,大约阅读时间需要 3 分钟。

在这里插入图片描述

限制空间、时间复杂度,所以无法用Map

位运算大显身手

4 ^ 1 ^ 4 ^ 6 => 1 ^ 66 对应的二进制: 1101 对应的二进制: 0011 ^ 6  二进制: 111

但是通过111无法得知是1^6

所以分组解决,奇数在一起,偶数在一起,各玩各的(异或)

class Solution {
public int[] singleNumbers(int[] nums) {
int k = 0; for (int num : nums) {
k ^= num; } int mask = 1; while ((k & mask) == 0) {
mask <<= 1; } int a = 0; int b = 0; for (int num : nums) {
if ((num & mask) == 0) {
a ^= num; } else {
b ^= num; } } return new int[] {
a, b }; }}
常见位运算X&1==1   X&1==0//判断奇数偶数X>>1//整除2X<<1//乘以2X=X&(X-1)//清零最低位的1X&-X//得到最低位的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&(n-1);//消除最低位的1 } return res; }}

在这里插入图片描述

class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0){
return false;} return (n&(n-1))==0; }}

这两道题都用到了,消除最低位的1公式。

转载地址:http://nsnwi.baihongyu.com/

你可能感兴趣的文章
3.7.1 - Strings
查看>>
3.7.4 - Indexing and Slicing Strings
查看>>
3.7.5 - Modifying Strings
查看>>
3.7.6 - String Methods
查看>>
3.8 - Using the Print Function
查看>>
3.9.1 - Lists in Python
查看>>
3.9.2 - Lists - Adding and Removing Objects
查看>>
3.9.3 - Sorting Lists
查看>>
3.10 - Maya Commands: ls
查看>>
3.11 - Dictionaries in Python
查看>>
3.12 - Tuples in Python
查看>>
4.4 - For Loops
查看>>
4.2.2 - Logical and/or Operators
查看>>
Lesson 4 Part 2 Softmax Regression
查看>>
文章中运用到的数学公式
查看>>
Projective Dynamics: Fusing Constraint Projections for Fast Simulation
查看>>
从2D恢复出3D的数据
查看>>
glm 中 数据类型 与 原始数据(c++ 数组)之间的转换
查看>>
Derivatives of scalars, vector functions and matrices
查看>>
the jacobian matrix and the gradient matrix
查看>>