给定一个非负整数N。任务是将数字N的位取反,并打印取反后获得的数字的十进制等效项。
注意:不考虑前导0。
例子:
Input : 11
Output : 4
(11)10 = (1011)2
After inverting the bits, we get:
(0100)2 = (4)10.
Input : 20
Output : 11
(20)10 = (10100)2.
After inverting the bits, we get:
(01011)2 = (11)10.
反转数字的实际位中已经讨论了类似的问题。
在本文中,讨论了一种使用按位运算运算符的有效方法。以下是解决问题的分步算法:
- 计算给定数字中的位数。可以通过计算来完成:
X = log2N
其中N是给定的数字,X是N的总位数。
- 下一步是生成一个X位且所有位均置1的数字。即11111….X倍。可以通过计算来完成:
Step-1: M = 1 << X Step-2: M = M | (M-1)
其中M是设置了所有位的所需X位数字。
- 最后一步是计算M与N的按位XOR,这将是我们的答案。
下面是上述方法的实现:
C++
// C++ program to invert actual bits
// of a number.
#include
using namespace std;
// Function to invert bits of a number
int invertBits(int n)
{
// Calculate number of bits of N-1;
int x = log2(n) ;
int m = 1 << x;
m = m | m - 1;
n = n ^ m;
return n;
}
// Driver code
int main()
{
int n = 20;
cout << invertBits(n);
return 0;
}
Java
// Java program to invert
// actual bits of a number.
import java.util.*;
class GFG
{
// Function to invert
// bits of a number
static int invertBits(int n)
{
// Calculate number of bits of N-1;
int x = (int)(Math.log(n) /
Math.log(2)) ;
int m = 1 << x;
m = m | m - 1;
n = n ^ m;
return n;
}
// Driver code
public static void main(String[] args)
{
int n = 20;
System.out.print(invertBits(n));
}
}
// This code is contributed by Smitha
Python3
# Python3 program to invert actual
# bits of a number.
import math
# Function to invert bits of a number
def invertBits(n):
# Calculate number of bits of N-1
x = int(math.log(n, 2))
m = 1 << x
m = m | m - 1
n = n ^ m
return n
# Driver code
n = 20
print(invertBits(n))
# This code is contributed 29AjayKumar
C#
// C# program to invert
// actual bits of a number.
using System;
public class GFG
{
// Function to invert
// bits of a number
static int invertBits(int n)
{
// Calculate number of bits of N-1;
int x = (int)(Math.Log(n) /
Math.Log(2)) ;
int m = 1 << x;
m = m | m - 1;
n = n ^ m;
return n;
}
// Driver code
public static void Main()
{
int n = 20;
Console.Write(invertBits(n));
}
}
// This code is contributed by Subhadeep
PHP
Javascript
输出:
11
时间复杂度:O(log 2 n)
辅助空间:O(1)