Problem Description
Given n hexadecimal positive integers, output their corresponding octal numbers.
1 Input format
The first line of input is a positive integer n (1<=n<=10).
In the next n lines, each line contains a string consisting of 0-9 and uppercase letters A~F, which represents the positive hexadecimal integer to be converted, and the length of each hexadecimal number does not exceed 100000.
2 Output format
Output n lines, each line corresponds to a positive octal integer.
【note】
The entered hexadecimal number will not have leading 0, such as 012A.
The output octal number can also not have leading 0.
3 Sample input
2
39
123 ABC
4 Sample output
71
4435274
solution
When direct conversion is difficult, you can find an "intermediate value". That is, octal-decimal-octal
Sample code
def jz(x):
s=0
a={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
x=str(x)[::-1]for i inrange(len(str(x))):#Convert decimal
if x[i]in a:
s+=a[x[i]]*16**i
else:
s+=int(x[i])*16**i
h=''while s>=1:#Convert binary
h+=str(s%2)
s=s//2
s=h#Binary
iflen(s)%3==0:
pass
else:
s+='0'*(3-len(s)%3)
p=''for i inrange(0,len(s),3):#Convert octal (3 from right to left as a group)
k=s[i:i+3][::-1]
t=int(k[0])*2**2+int(k[1])*2**1+int(k[2])*2**0
p+=str(t)returnint(p[::-1])
n=int(input())for i inrange(n):
g=input()print(jz(g))
Conclusion
The arrangement of the digits in the decimal system is like this...
The arrangement of digits in the R base is like this......R^4 R^3R^2 R^1 R^0 R^-1 R^-2 R^-3......
Law: The difference between adjacent digits is the first power of the system.
E.g:
Decimal 123=1×100+2×10+3×1
9876 in decimal = 9×1000+8×100+7×10+6×1
The rule of base conversion is very simple, but many people don't know it, and the actual operation is very easy to make mistakes.
END
Recommended Posts