
题目描述
给你一个整数 n
。
返回 n2
的 十六进制表示 和 n3
的 三十六进制表示 拼接成的字符串。
十六进制 数定义为使用数字 0 – 9
和大写字母 A - F
表示 0 到 15 的值。
三十六进制 数定义为使用数字 0 – 9
和大写字母 A - Z
表示 0 到 35 的值。
示例 1:
输入:n = 13
输出: "A91P1"
解释:
n2 = 13 * 13 = 169
。在十六进制中,它转换为 (10 * 16) + 9 = 169
,对应于 "A9"
。
n3 = 13 * 13 * 13 = 2197
。在三十六进制中,它转换为 (1 * 362) + (25 * 36) + 1 = 2197
,对应于 "1P1"
。
- 连接两个结果得到
"A9" + "1P1" = "A91P1"
。
示例 2:
输入:n = 36
输出:"5101000"
解释:
n2 = 36 * 36 = 1296
。在十六进制中,它转换为 (5 * 162) + (1 * 16) + 0 = 1296
,对应于 "510"
。
n3 = 36 * 36 * 36 = 46656
。在三十六进制中,它转换为 (1 * 363) + (0 * 362) + (0 * 36) + 0 = 46656
,对应于 "1000"
。
- 连接两个结果得到
"510" + "1000" = "5101000"
。
提示:
解法
方法一:模拟
我们定义一个函数 \(\textit{f}(x, k)\),它将整数 \(x\) 转换为以 \(k\) 进制表示的字符串。该函数通过不断取模和整除来构建结果字符串。
对于给定的整数 \(n\),我们计算 \(n^2\) 和 \(n^3\),然后分别将它们转换为十六进制和三十六进制字符串。最后,将这两个字符串连接起来返回。
时间复杂度 \(O(\log n)\),空间复杂度 \(O(1)\)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | class Solution:
def concatHex36(self, n: int) -> str:
def f(x: int, k: int) -> str:
res = []
while x:
v = x % k
if v <= 9:
res.append(str(v))
else:
res.append(chr(ord("A") + v - 10))
x //= k
return "".join(res[::-1])
x, y = n**2, n**3
return f(x, 16) + f(y, 36)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 | class Solution {
public String concatHex36(int n) {
int x = n * n;
int y = n * n * n;
return f(x, 16) + f(y, 36);
}
private String f(int x, int k) {
StringBuilder res = new StringBuilder();
while (x > 0) {
int v = x % k;
if (v <= 9) {
res.append((char) ('0' + v));
} else {
res.append((char) ('A' + v - 10));
}
x /= k;
}
return res.reverse().toString();
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 | class Solution {
public:
string concatHex36(int n) {
int x = n * n;
int y = n * n * n;
return f(x, 16) + f(y, 36);
}
private:
string f(int x, int k) {
string res;
while (x > 0) {
int v = x % k;
if (v <= 9) {
res += char('0' + v);
} else {
res += char('A' + v - 10);
}
x /= k;
}
reverse(res.begin(), res.end());
return res;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | func concatHex36(n int) string {
x := n * n
y := n * n * n
return f(x, 16) + f(y, 36)
}
func f(x, k int) string {
res := []byte{}
for x > 0 {
v := x % k
if v <= 9 {
res = append(res, byte('0'+v))
} else {
res = append(res, byte('A'+v-10))
}
x /= k
}
for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
res[i], res[j] = res[j], res[i]
}
return string(res)
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | function concatHex36(n: number): string {
function f(x: number, k: number): string {
const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let res = '';
while (x > 0) {
const v = x % k;
res = digits[v] + res;
x = Math.floor(x / k);
}
return res;
}
const x = n * n;
const y = n * n * n;
return f(x, 16) + f(y, 36);
}
|