Skip to content

Commit ad7723f

Browse files
Charliieeafonsocarlos
authored andcommitted
Add Python implementation for sparse_number
1 parent e7748e1 commit ad7723f

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def is_sparse(n):
2+
# a number n is sparse if there are no two
3+
# adjacent 1's in its binary representation
4+
# ex: 5 (101) is sparse, but 6 (110) is not
5+
# Therefore, a sparse number when shifted one position
6+
# will have no collapsing 1's on an AND operation
7+
return not n & (n>>1)
8+
9+
10+
if __name__ == "__main__":
11+
n = int(input())
12+
print(is_sparse(n))

0 commit comments

Comments
 (0)