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
20
21
#include <cassert>
22
#include <cstdint>
23
#include <iostream>
24
29
namespace
bit_manipulation
{
37
namespace
set_kth_bit {
43
std::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
61
static
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
}
73
77
int
main
() {
78
test
();
// run self-test implementations
79
return
0;
80
}
bit_manipulation
for assert
setKthBit
Functions for the [From the right, set the Kth bit in the binary representation of N] (https://practi...
test
static void test()
Self-test implementations.
Definition
set_kth_bit.cpp:61
bit_manipulation::set_kth_bit::setKthBit
std::uint64_t setKthBit(std ::int64_t N, std ::int64_t k)
The main function implements set kth bit.
Definition
set_kth_bit.cpp:43
main
int main()
Main function.
Definition
set_kth_bit.cpp:77
bit_manipulation
set_kth_bit.cpp
Generated by
1.13.2