Skip to content

Commit 749f7c6

Browse files
committed
feat: add solutions to lcci problem: No.05.06
No.05.06.Convert Integer
1 parent 7c69318 commit 749f7c6

File tree

5 files changed

+71
-4
lines changed

5 files changed

+71
-4
lines changed

lcci/05.06.Convert Integer/README.md

+31-2
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,24 @@
3131

3232
<!-- 这里可写通用的实现逻辑 -->
3333

34+
**方法一:位运算**
35+
36+
我们将 A 和 B 进行异或运算,得到的结果中 $1$ 的个数即为需要改变的位数。
37+
38+
时间复杂度 $O(\log n)$,其中 $n$ 为 A 和 B 的最大值。空间复杂度 $O(1)$。
39+
3440
<!-- tabs:start -->
3541

3642
### **Python3**
3743

3844
<!-- 这里可写当前语言的特殊实现逻辑 -->
3945

4046
```python
41-
42-
47+
class Solution:
48+
def convertInteger(self, A: int, B: int) -> int:
49+
A &= 0xFFFFFFFF
50+
B &= 0xFFFFFFFF
51+
return (A ^ B).bit_count()
4352
```
4453

4554
### **Java**
@@ -54,6 +63,26 @@ class Solution {
5463
}
5564
```
5665

66+
### **C++**
67+
68+
```cpp
69+
class Solution {
70+
public:
71+
int convertInteger(int A, int B) {
72+
unsigned int c = A ^ B;
73+
return __builtin_popcount(c);
74+
}
75+
};
76+
```
77+
78+
### **Go**
79+
80+
```go
81+
func convertInteger(A int, B int) int {
82+
return bits.OnesCount32(uint32(A ^ B))
83+
}
84+
```
85+
5786
### **TypeScript**
5887

5988
```ts

lcci/05.06.Convert Integer/README_EN.md

+25-2
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,11 @@
5151
### **Python3**
5252

5353
```python
54-
55-
54+
class Solution:
55+
def convertInteger(self, A: int, B: int) -> int:
56+
A &= 0xFFFFFFFF
57+
B &= 0xFFFFFFFF
58+
return (A ^ B).bit_count()
5659
```
5760

5861
### **Java**
@@ -65,6 +68,26 @@ class Solution {
6568
}
6669
```
6770

71+
### **C++**
72+
73+
```cpp
74+
class Solution {
75+
public:
76+
int convertInteger(int A, int B) {
77+
unsigned int c = A ^ B;
78+
return __builtin_popcount(c);
79+
}
80+
};
81+
```
82+
83+
### **Go**
84+
85+
```go
86+
func convertInteger(A int, B int) int {
87+
return bits.OnesCount32(uint32(A ^ B))
88+
}
89+
```
90+
6891
### **TypeScript**
6992

7093
```ts
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution {
2+
public:
3+
int convertInteger(int A, int B) {
4+
unsigned int c = A ^ B;
5+
return __builtin_popcount(c);
6+
}
7+
};
+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
func convertInteger(A int, B int) int {
2+
return bits.OnesCount32(uint32(A ^ B))
3+
}
+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class Solution:
2+
def convertInteger(self, A: int, B: int) -> int:
3+
A &= 0xFFFFFFFF
4+
B &= 0xFFFFFFFF
5+
return (A ^ B).bit_count()

0 commit comments

Comments
 (0)