Skip to content

Commit d1fca7f

Browse files
Add files via upload
1 parent d06ca13 commit d1fca7f

File tree

2 files changed

+103
-0
lines changed

2 files changed

+103
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// 典型的位运算的题目 解题思路很巧妙
2+
// 思路一,比较低效
3+
4+
// Runtime: 8 ms, faster than 95.68% of C++ online submissions for Bitwise AND of Numbers Range.
5+
// Memory Usage: 8.6 MB, less than 5.45% of C++ online submissions for Bitwise AND of Numbers Range.
6+
7+
class Solution
8+
{
9+
public:
10+
int rangeBitwiseAnd(int m, int n)
11+
{
12+
vector<bool> memo(31, false);
13+
14+
for (int i = 0; i < 31; i++)
15+
{
16+
if (m == n && m & 1 == 1)
17+
memo[i] = true;
18+
19+
m >>= 1;
20+
n >>= 1;
21+
22+
if (m == 0 && n == 0)
23+
break;
24+
}
25+
26+
// 计算最终的结果
27+
int res = 0;
28+
for (int i = 30; i >= 0; i--)
29+
{
30+
res <<= 1;
31+
if (memo[i])
32+
res++;
33+
}
34+
35+
return res;
36+
}
37+
};
38+
39+
// 思路二 相对高效
40+
41+
// Runtime: 8 ms, faster than 95.68% of C++ online submissions for Bitwise AND of Numbers Range.
42+
// Memory Usage: 8 MB, less than 89.81% of C++ online submissions for Bitwise AND of Numbers Range.
43+
44+
class Solution
45+
{
46+
public:
47+
int rangeBitwiseAnd(int m, int n)
48+
{
49+
if (m == 0 || n == 0)
50+
return 0;
51+
52+
int factor = 0;
53+
while (m != n)
54+
{
55+
m >>= 1;
56+
n >>= 1;
57+
factor++;
58+
}
59+
60+
return m << factor;
61+
}
62+
};
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# 思路一的py代码
2+
3+
class Solution:
4+
def rangeBitwiseAnd(self, m: int, n: int) -> int:
5+
memo = [False] * 31
6+
7+
for i in range(31):
8+
if m == n and m & 1 is 1:
9+
memo[i] = True
10+
m >>= 1
11+
n >>= 1
12+
13+
if m is 0 and n is 0:
14+
break
15+
16+
res = 0
17+
for i in range(30, -1, -1):
18+
res <<= 1
19+
if memo[i]:
20+
res += 1
21+
22+
return res
23+
24+
# 思路二的py代码
25+
26+
# Runtime: 60 ms, faster than 86.48% of Python3 online submissions for Bitwise AND of Numbers Range.
27+
# Memory Usage: 13.4 MB, less than 21.68% of Python3 online submissions for Bitwise AND of Numbers Range.
28+
29+
class Solution:
30+
def rangeBitwiseAnd(self, m: int, n: int) -> int:
31+
32+
if m is 0 and n is 0:
33+
return 0
34+
35+
factor = 0
36+
while m != n:
37+
m >>= 1
38+
n >>= 1
39+
factor += 1
40+
41+
return m << factor

0 commit comments

Comments
 (0)