TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
set_kth_bit.cpp
Go to the documentation of this file.
1
21#include <cassert>
22#include <cstdint>
23#include <iostream>
24
29namespace bit_manipulation {
37namespace set_kth_bit {
43std::uint64_t setKthBit(std ::int64_t N,
44 std ::int64_t k) { // int64_t is preferred over int so
45 // that no Overflow can be there.
46
47 int pos =
48 1 << k; // "pos" variable is used to store 1 at kth postion and
49 // rest bits are 0. in binary representation of number 'n'
50
51 return N | pos; // by taking or with the pos and the N we set the bit of N
52 // at kth position.
53}
54} // namespace set_kth_bit
55} // namespace bit_manipulation
56
61static void test() {
62 // n = 10,2 return 14
63 assert(bit_manipulation::set_kth_bit::setKthBit(10, 2) == 14);
64 // n = 25,1 return 27
65 assert(bit_manipulation::set_kth_bit::setKthBit(25, 1) == 27);
66 // n = 400001,5 return 400033
67 assert(bit_manipulation::set_kth_bit::setKthBit(400001, 5) == 400033);
68 // n = 123 return 123
69 assert(bit_manipulation::set_kth_bit::setKthBit(123, 3) == 123);
70
71 std::cout << "All test cases successfully passed!" << std::endl;
72}
77int main() {
78 test(); // run self-test implementations
79 return 0;
80}
Functions for the [From the right, set the Kth bit in the binary representation of N] (https://practi...
static void test()
Self-test implementations.
int main()
Main function.