Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
  • 哈希表

  • 双指针

  • 数组

  • 字符串

  • 链表

  • 树

  • 回溯

  • 动态规划

  • 图

  • 二分查找

  • 贪心

  • 栈&队列

  • 堆

  • 位运算

    • 位运算
      • 7. 整数反转
      • 9. 回文数
      • 136. 只出现一次的数字
      • 191. 位1的个数
    • 位运算总结
  • 数据结构设计

  • rui的精选题单

  • 笔试真题

  • LeetCode周赛

  • ACM模式输入输出
  • 数学

  • 数据结构与算法
  • 位运算
Nreal
2024-01-19
目录

位运算

# 7. 整数反转 (opens new window)

class Solution {
    public int reverse(int x) {
        int ret = 0;
        while(x!=0){
            if(ret>Integer.MAX_VALUE/10 || ret<Integer.MIN_VALUE/10)
                return 0;
            ret = ret*10 + x%10;
            x /= 10;
        }
        return ret;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

# 9. 回文数 (opens new window)

class Solution {
    public boolean isPalindrome(int x) {
        // 负数不是回文,最后一位数字为0则第一位数字也得为0
        if(x<0 || (x%10==0&&x!=0))
            return false;
        int rev = 0;
        while(x>rev){
            rev = rev*10 + x%10;
            x /= 10;
        }
        // 数字长度分为 奇数或偶数
        return x==rev || x==rev/10;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 136. 只出现一次的数字 (opens new window)

方法一:位运算

class Solution {
    public int singleNumber(int[] nums) {
        int ret = 0;
        for(int num:nums){
            ret ^= num;
        }
        return ret;
    }
}
1
2
3
4
5
6
7
8
9

方法二:API

public class Solution {
    public int hammingWeight(int n) {
        return Integer.bitCount(n);
    }
}
1
2
3
4
5

# 191. 位1的个数 (opens new window)

方法一:逐位判断

class Solution {
    public int hammingWeight(int n) {
        int res = 0;
        while(n!=0){
            res += n&1;
            n >>>= 1;
        }
        return res;
    }
}
1
2
3
4
5
6
7
8
9
10

方法二:n&(n-1)

最右边的1变为0;

class Solution {
    public int hammingWeight(int n) {
        int res = 0;
        while(n!=0){
            res++;
            n &= (n-1);
        }
        return res;
    }
}
1
2
3
4
5
6
7
8
9
10
优先级队列
位运算总结

← 优先级队列 位运算总结→

Theme by Vdoing | Copyright © 2021-2024
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式