📌  相关文章
📜  翻转给定数字的所有K位

📅  最后修改于: 2021-05-25 10:32:52             🧑  作者: Mango

给定两个整数NK ,任务是用K位表示N并打印翻转所有位后获得的数字。

例子:

方法:请按照以下步骤解决问题:

  • 找到(1 <<((K – 1))– 1的值,说X。
  • 最后,打印(X – N)的值。

下面是上述方法的实现:

C++
// C++ Program for the above approach
 
#include 
using namespace std;
 
// Function to flip all K-bits
// of an unsigned number N
void flippingBits(unsigned long N,
                  unsigned long K)
{
 
    // Stores (2 ^ K) - 1
    unsigned long X = (1 << (K - 1)) - 1;
 
    // Update N
    N = X - N;
 
    // Print the answer
    cout << N;
}
 
// Driver Code
int main()
{
    unsigned long N = 1, K = 8;
    flippingBits(N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to flip all K-bits
// of an unsigned number N
static void flippingBits(long N,
                         long K)
{
     
    // Stores (2 ^ K) - 1
    long X = (1 << (K - 1)) - 1;
     
    // Update N
    N = X - N;
     
    // Print the answer
    System.out.print(N);
}
 
// Driver Code
public static void main(String[] args)
{
    long N = 1, K = 8;
     
    flippingBits(N, K);
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 Program for the above approach
 
# Function to flip all K-bits
# of an unsigned number N
def flippingBits(N, K):
 
    # Stores (2 ^ K) - 1
    X = (1 << (K - 1)) - 1
 
    # Update N
    N = X - N
 
    # Print the answer
    print(N)
 
# Driver Code
if __name__ == '__main__':
    N, K = 1, 8
    flippingBits(N, K)
 
    # This code is contribute by mohit kumar 29


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to flip all K-bits
// of an unsigned number N
static void flippingBits(int N, int K)
{
     
    // Stores (2 ^ K) - 1
    int X = (1 << (K - 1)) - 1;
 
    // Update N
    N = X - N;
 
    // Print the answer
    Console.Write(N);
}
 
// Driver Code
public static void Main(string[] args)
{
    int N = 1, K = 8;
     
    flippingBits(N, K);
}
}
 
// This code is contributed by chitranayal


Javascript


输出:
126

时间复杂度: O(1)
辅助空间: O(1)