要将一个整数转换为 7 进制,可以使用以下方法:
首先,如果输入的数字是负数,可以将其转换为正数,并在最后加上负号。
然后,使用循环进行如下操作:
- 将数字除以 7,并记录余数。
- 将数字赋值为商。
- 循环结束后,将所有余数倒序排列,并将它们连接起来。
以下是 Python 代码示例:
def convertToBase7(num):
if num == 0:
return "0"
res = ""
is_negative = False
if num < 0:
is_negative = True
num = -num
while num > 0:
res = str(num % 7) + res
num //= 7
if is_negative:
res = "-" + res
return res