Yra's blog Yra's blog
Homepage
  • LeetCode周赛
  • Acwing周赛
  • 刷题整理
  • 题解
  • CPP
  • Golang
  • System

    • MIT6.S081 Labs
  • Computer Networking

    • CS144: Computer Networking
  • DataBase

    • MySQL
    • Redis
  • Others

    • ......
  • Paper Reading

    • Petri Net
  • Static Analysis

    • NJU Course Notes
  • Deep Learning

    • Dive into Deep Learning
Casual Records
Archives

Yra

Only a vegetable dog.
Homepage
  • LeetCode周赛
  • Acwing周赛
  • 刷题整理
  • 题解
  • CPP
  • Golang
  • System

    • MIT6.S081 Labs
  • Computer Networking

    • CS144: Computer Networking
  • DataBase

    • MySQL
    • Redis
  • Others

    • ......
  • Paper Reading

    • Petri Net
  • Static Analysis

    • NJU Course Notes
  • Deep Learning

    • Dive into Deep Learning
Casual Records
Archives
  • System

  • Computer Networking

  • DataBase

  • Software Engineering

  • Others

    • 通过 Bit-Manipulation 实现 abs 函数
      • 408 计组笔记
    • Learning Notes
    • Others
    Yra
    2022-09-10
    目录

    通过 Bit-Manipulation 实现 abs 函数

    # 题意

    实现函数 int abs(int x),当 时,返回 ,当 时,返回 。

    # 代码

    先说结论:

      int abs(int x) {
          return (x >> 31 ^ x) - (x >> 31);
      }
      
      // Make sure to add code blocks to your code group

      # 分析

      首先我们要知道如果通过位运算来得到一个数的相反数。我们可以通过 ~x + 1,即对一个数取反加一就能得到该数的相反数,这是因为 ~x + x = 0b11111...,而 0b11111...就是二进制补码下的 -1,我们再加 1,就能得到 0 了。因此 (~x + 1) + x = 0,即 ~x + 1 是 x 的相反数。

      我们对答案 (x >> 31 ^ x) - (x >> 31)进行分析:

      当 时,因为是 signed int,会进行算术右移,所以 x >> 31 会得到 0b11111...,即 -1, 很容易发现,此时 -1 ^ x 就相当于对每一个二进制位进行取反。而后面的 - (x >> 31) 很容易看出就是 + 1,整体就是 return ~x + 1;

      当 时,x >> 31 会得到 0b00000...,此时进行异或操作后得到的结果还是 x,而后面则是个 - 0,整体就是 return x - 0;

      综上,我们便可以通过位运算实现 abs 函数了。

      #Learning Notes#Others
      Last Updated: 9/21/2023, 10:59:25 PM
      03 - 用例建模
      408 计组笔记

      ← 03 - 用例建模 408 计组笔记→

      最近更新
      01
      408 计组笔记
      07-19
      02
      Dive into Deep Learning
      01-27
      03
      25 考研随记
      11-27
      更多文章>
      Theme by Vdoing | Copyright © 2022-2025
      • 跟随系统
      • 浅色模式
      • 深色模式
      • 阅读模式