File tree 5 files changed +71
-4
lines changed
lcci/05.06.Convert Integer
5 files changed +71
-4
lines changed Original file line number Diff line number Diff line change 31
31
32
32
<!-- 这里可写通用的实现逻辑 -->
33
33
34
+ ** 方法一:位运算**
35
+
36
+ 我们将 A 和 B 进行异或运算,得到的结果中 $1$ 的个数即为需要改变的位数。
37
+
38
+ 时间复杂度 $O(\log n)$,其中 $n$ 为 A 和 B 的最大值。空间复杂度 $O(1)$。
39
+
34
40
<!-- tabs:start -->
35
41
36
42
### ** Python3**
37
43
38
44
<!-- 这里可写当前语言的特殊实现逻辑 -->
39
45
40
46
``` python
41
-
42
-
47
+ class Solution :
48
+ def convertInteger (self , A : int , B : int ) -> int :
49
+ A &= 0x FFFFFFFF
50
+ B &= 0x FFFFFFFF
51
+ return (A ^ B).bit_count()
43
52
```
44
53
45
54
### ** Java**
@@ -54,6 +63,26 @@ class Solution {
54
63
}
55
64
```
56
65
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
+
57
86
### ** TypeScript**
58
87
59
88
``` ts
Original file line number Diff line number Diff line change 51
51
### ** Python3**
52
52
53
53
``` python
54
-
55
-
54
+ class Solution :
55
+ def convertInteger (self , A : int , B : int ) -> int :
56
+ A &= 0x FFFFFFFF
57
+ B &= 0x FFFFFFFF
58
+ return (A ^ B).bit_count()
56
59
```
57
60
58
61
### ** Java**
@@ -65,6 +68,26 @@ class Solution {
65
68
}
66
69
```
67
70
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
+
68
91
### ** TypeScript**
69
92
70
93
``` ts
Original file line number Diff line number Diff line change
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
+ };
Original file line number Diff line number Diff line change
1
+ func convertInteger (A int , B int ) int {
2
+ return bits .OnesCount32 (uint32 (A ^ B ))
3
+ }
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def convertInteger (self , A : int , B : int ) -> int :
3
+ A &= 0xFFFFFFFF
4
+ B &= 0xFFFFFFFF
5
+ return (A ^ B ).bit_count ()
You can’t perform that action at this time.
0 commit comments