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

📅  最后修改于: 2021-10-26 02:29:03             🧑  作者: Mango

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

例子:

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

  • 这个想法是创建一个形式为111111100000…的掩码。
  • 要创建掩码,请从所有掩码开始,如1111111111…
  • 有两种可能的选项来生成全 1。通过用1翻转所有0或使用 2 补码并将其左移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)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程