Skip to content

Commit 24faa73

Browse files
committed
Bitwise AND of Numbers Range/ Happy Number
1 parent eda1d89 commit 24faa73

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

201 Bitwise AND of Numbers Range.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'''
2+
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
3+
4+
For example, given the range [5, 7], you should return 4.
5+
'''
6+
7+
class Solution(object):
8+
def rangeBitwiseAnd(self, m, n):
9+
"""
10+
:type m: int
11+
:type n: int
12+
:rtype: int
13+
"""
14+
while n > m:
15+
n &= n - 1
16+
return n
17+
18+
19+
if __name__ == "__main__":
20+
assert Solution().rangeBitwiseAnd(5, 7) == 4
21+
assert Solution().rangeBitwiseAnd(7, 15) == 0

202 Happy Number.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'''
2+
Write an algorithm to determine if a number is "happy".
3+
4+
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
5+
6+
Example: 19 is a happy number
7+
8+
1^2 + 9^2 = 82
9+
8^2 + 2^2 = 68
10+
6^2 + 8^2 = 100
11+
1^2 + 0^2 + 0^2 = 1
12+
'''
13+
14+
class Solution(object):
15+
def isHappy(self, n):
16+
"""
17+
:type n: int
18+
:rtype: bool
19+
"""
20+
visited = []
21+
while n != 1:
22+
if n in visited:
23+
return False
24+
visited.append(n)
25+
n = sum([int(i) ** 2 for i in str(n)])
26+
return True
27+
28+
29+
if __name__ == "__main__":
30+
assert Solution().isHappy(19) == True

0 commit comments

Comments
 (0)