Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit af5c50a

Browse files
committed
[20230507] Solve BitManipulation easy problems
1 parent 7d888f5 commit af5c50a

File tree

4 files changed

+51
-0
lines changed

4 files changed

+51
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# 191. Number of 1 Bits
2+
# https://leetcode.com/problems/number-of-1-bits/description/
3+
4+
class Solution:
5+
def hammingWeight(self, n: int) -> int:
6+
i = 0
7+
count = 0
8+
while i < 32:
9+
if n & 1 == 1:
10+
count += 1
11+
n = n >> 1
12+
i += 1
13+
return count
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# 231. Power of Two
2+
# https://leetcode.com/problems/power-of-two/
3+
4+
class Solution:
5+
def isPowerOfTwo(self, n: int) -> bool:
6+
r, i = 1, 0
7+
while i <= 32:
8+
if n ^ r == 0:
9+
return True
10+
r = r << 1
11+
i += 1
12+
return False
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# 1486. XOR Operation in an Array
2+
# https://leetcode.com/problems/xor-operation-in-an-array/description/
3+
4+
class Solution:
5+
def xorOperation(self, n: int, start: int) -> int:
6+
r = start
7+
i = 1
8+
while i < n:
9+
r = r ^ (start + 2 * i)
10+
i += 1
11+
return r
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# 1720. Decode XORed Array
2+
# https://leetcode.com/problems/decode-xored-array/description/
3+
4+
from typing import List
5+
6+
7+
class Solution:
8+
def decode(self, encoded: List[int], first: int) -> List[int]:
9+
# xor 연산은 한번 더 하면 원래 값이 나온다.
10+
result = [first]
11+
i = 1
12+
for e in encoded:
13+
result.append(result[i - 1] ^ e)
14+
i += 1
15+
return result

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /