Join Regular Classroom : Visit ClassroomTech

Accenture Coding Question | Turn off Bit | CodeWindow

Turn Off Bit

The function accepts a positive integer array ‘n’ and position of the bit to be turned off ‘k’. Implement the function to turn off the kth bit of the binary representation of ‘n’ and return decimal equivalent of the obtained number. Consider position of ‘k’ according to “little Endian’ notation (i.e. right to left).

Assumptions:
k>0
The number of bits of the binary representation of ‘n’ is >=k

Note:
When counting the bits from right to left, start counting from 1.
Return ‘n’, if kth bit is already off.

Example:
Input:
n: 19
k: 2

Output: 17

Explanation:
n : 19
Binary Representation of n : 10011
k : 2
Binary Representation of number after turning off kth bit : 10001
return Value : 17

Sample Input:
n : 13
k : 3

Sample Output :
9

Solution in Python 3:

# https://codewindow.in

x=int(input())
#x=19
y=int(input())
#y=2
x=list(bin(x))
#x=bin(19) => 'ob10011'
#list('ob10011')==> ['o','b,'1','0','0','1','1']
print(x)
#['o','b,'1','0','0','1','1']

x[-y]='0' 
#Right to Left. So, Negative Indexing. then Set '0'
#['o','b,'1','0','0','0','1']
print(int("".join(x[2:]),2))

#join Telegram @codewindow

Solution in C++ :

//https://codewindow.in
//join our telegram channel @codewindow

#include <iostream>

using namespace std;

int main()
{
    int n,k;
    cin >> n;
    cin >> k;
    cout << (n & ~(1 << (k - 1)));
}

Solution in C :

//https://codewindow.in
//join our telegram channel @codewindow

#include <stdio.h>

int main()
{
    int n,k;
    scanf("%d",&n);
    scanf("%d",&k);
    printf("%d",(n & ~(1 << (k - 1))));
}

Solution in JAVA :

//https://codewindow.in
//join our telegram channel @codewindow
import java.util.*;

class CodeWindow {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        System.out.println(n & ~(1 << (k - 1)));
    }
}

Output:

13
3
9
Recent Posts
Pages