日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

leetcode 476. 数字的补数(Java版)| How to extract ‘k’ bits from a given position in a number

發布時間:2024/2/28 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 476. 数字的补数(Java版)| How to extract ‘k’ bits from a given position in a number 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

https://leetcode-cn.com/problems/number-complement/


思路

我們想要返回已知數字的補數(num>=1)。

思路:

  • 獲取 num 的二進制數
  • 將 num 的二進制數取反
  • 由于取反后,所有高位的 0 都會變為1,所以需要截取有效的低位,得到真正的返回結果
  • * 參考:How to extract ‘k’ bits from a given position in a number

    https://www.geeksforgeeks.org/extract-k-bits-given-position-number/

    How to extract ‘k’ bits from a given position ‘p’ in a number?

    Examples:

    Input : number = 171k = 5 p = 2 Output : The extracted number is 21 171 is represented as 0101011 in binary, so, you should get only 10101 i.e. 21. (從第2位開始,向左取5位)Input : number = 72k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get only 01000 i.e 8.
  • Right shift number by p-1.
  • Do bit wise AND of k set bits with the modified number. We can get k set bits by doing (1 << k) – 1.
  • Example:

    // Java program to extract k bits from a given // position.class GFG {// Function to extract k bits from p position// and returns the extracted value as integerstatic int bitExtracted(int number, int k, int p){return (((1 << k) - 1) & (number >> (p - 1)));}// Driver codepublic static void main (String[] args) {int number = 171, k = 5, p = 2;System.out.println("The extracted number is "+bitExtracted(number, k, p));} }

    Output:

    The extracted number is 21

    代碼

    1、易懂版
    public class Solution {/*** 給你一個正整數 num ,輸出它的補數。補數是對該數的二進制表示取反。*/public static int findComplement(int num) {int bitLen = Integer.toBinaryString(num).length();return bitExtracted(~num, bitLen, 1);}// Function to extract k bits from p position// and returns the extracted value as integerstatic int bitExtracted(int number, int leftIndex, int rightIndex) {System.out.println(Integer.toBinaryString(number));int i = ((1 << leftIndex) - 1) & (number >> (rightIndex - 1));System.out.println(Integer.toBinaryString(i));return i;} }
    2、簡化版
    class Solution {public int findComplement(int num) {int bitLen=Integer.toBinaryString(num).length();return ((1 << bitLen) - 1) & ~num;} }

    總結

    以上是生活随笔為你收集整理的leetcode 476. 数字的补数(Java版)| How to extract ‘k’ bits from a given position in a number的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。