leetcode 476. 数字的补数(Java版)| How to extract ‘k’ bits from a given position in a number
生活随笔
收集整理的這篇文章主要介紹了
leetcode 476. 数字的补数(Java版)| How to extract ‘k’ bits from a given position in a number
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode-cn.com/problems/number-complement/
思路
我們想要返回已知數字的補數(num>=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.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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 463. 岛屿的周长(
- 下一篇: leetcode 482. 密钥格式化(