FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms/algorithms/bit/insert_bit.py at master · lualgorithm/algorithms · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
lualgorithm
/
algorithms
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms
/
algorithms
/
bit
/
insert_bit.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
44 lines (37 loc) · 1.17 KB
Breadcrumbs
algorithms
/
algorithms
/
bit
/
insert_bit.py
Copy path
File metadata and controls
44 lines (37 loc) · 1.17 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
Insertion:
insert_one_bit(num, bit, i): insert exact one bit at specific position
For example:
Input: num = 10101 (21)
insert_one_bit(num, 1, 2): 101101 (45)
insert_one_bit(num, 0, 2): 101001 (41)
insert_one_bit(num, 1, 5): 110101 (53)
insert_one_bit(num, 1, 0): 101011 (43)
insert_mult_bits(num, bits, len, i): insert multiple bits with len at specific position
For example:
Input: num = 101 (5)
insert_mult_bits(num, 7, 3, 1): 101111 (47)
insert_mult_bits(num, 7, 3, 0): 101111 (47)
insert_mult_bits(num, 7, 3, 3): 111101 (61)
"""
"""
Insert exact one bit at specific position
Algorithm:
1. Create a mask having bit from i to the most significant bit, and append the new bit at 0 position
2. Keep the bit from 0 position to i position ( like 000...001111)
3. Merge mask and num
"""
def
insert_one_bit
(
num
,
bit
,
i
):
# Create mask
mask
=
num
>>
i
mask
=
(
mask
<<
1
)
|
bit
mask
=
mask
<<
i
# Keep the bit from 0 position to i position
right
=
((
1
<<
i
)
-
1
)
&
num
return
right
|
mask
def
insert_mult_bits
(
num
,
bits
,
len
,
i
):
mask
=
num
>>
i
mask
=
(
mask
<<
len
)
|
bits
mask
=
mask
<<
i
right
=
((
1
<<
i
)
-
1
)
&
num
return
right
|
mask
Back
|
FazBrowse Home
|
New Git URL