📜  给定数字的未设置最低有效K位

📅  最后修改于: 2021-04-27 09:34:32             🧑  作者: Mango

给定整数N ,任务是打印通过从N取消设置最低有效K位获得的数字。

例子:

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

  • 这个想法是创建一个111111100000…形式的蒙版。
  • 要创建遮罩,请从1111111111…开始
  • 有两种可能的方法来产生全1。或者通过与1秒翻转所有0秒或通过使用二进制补,并通过K比特左移它生成它。
  • 最后,从右到左打印K +1的值,因为它是从零开始的索引。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to return the value
// after unsetting K LSBs
int clearLastBit(int N, int K)
{
    // Create a mask
    int mask = (-1 << K + 1);
 
    // Bitwise AND operation with
    // the number and the mask
    return N = N & mask;
}
 
// Driver Code
int main()
{
    // Given N and K
    int N = 730, K = 3;
 
    // Function Call
    cout << clearLastBit(N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to return the value
// after unsetting K LSBs
static int clearLastBit(int N, int K)
{
    // Create a mask
    int mask = (-1 << K + 1);
 
    // Bitwise AND operation with
    // the number and the mask
    return N = N & mask;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given N and K
    int N = 730, K = 3;
 
    // Function Call
    System.out.print(clearLastBit(N, K));
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program for the above approach
 
# Function to return the value
# after unsetting K LSBs
def clearLastBit(N, K):
 
    # Create a mask
    mask = (-1 << K + 1)
 
    # Bitwise AND operation with
    # the number and the mask
    N = N & mask
 
    return N
 
# Driver Code
 
# Given N and K
N = 730
K = 3
 
# Function call
print(clearLastBit(N, K))
 
# This code is contributed by Shivam Singh


C#
// C# program for the above approach
using System;
class GFG{
 
// Function to return the value
// after unsetting K LSBs
static int clearLastBit(int N,
                        int K)
{
  // Create a mask
  int mask = (-1 << K + 1);
 
  // Bitwise AND operation with
  // the number and the mask
  return N = N & mask;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given N and K
  int N = 730, K = 3;
 
  // Function Call
  Console.Write(clearLastBit(N, K));
}
}
 
// This code is contributed by shikhasingrajput


Javascript


输出:
720

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