洛谷 p1010 幂次方 python实现
描述
任何一个正整数都可以用2的幂次方表示。例如 137= 2 7 + 2 3 + 2 0 2^7+2^3+2^0 27+23+20
同时约定方次用括号来表示,即 a b = a ( b ) a^b=a(b) ab=a(b)
由此可知,137可表示为 2 ( 7 ) + 2 ( 3 ) + 2 ( 0 ) 2(7)+2(3)+2(0) 2(7)+2(3)+2(0)
进一步:
7 = 2 2 + 2 + 2 0 7= 2^2+2+2^0 7=22+2+20( 2 1 2^1 21用2表示),并且 3 = 2 + 2 0 3=2+2^0 3=2+20
所以最后137可表示为
2 ( 2 ( 2 ) + 2 + 2 ( 0 ) ) + 2 ( 2 + 2 ( 0 ) ) + 2 ( 0 ) 2 ( 2 ( 2 ) + 2 + 2 ( 0 ) ) + 2 ( 2 + 2 ( 0 ) ) + 2 ( 0 ) 2(2(2)+2+2(0))+2(2+2(0))+2(0)2(2(2)+2+2(0))+2(2+2(0))+2(0) 2(2(2)+2+2(0))+2(2+2(0))+2(0)2(2(2)+2+2(0))+2(2+2(0))+2(0)
输入
一行一个正整数 n n n。
输出
符合约定的 n n n 的 0 , 2 0,2 0,2 表示(在表示中不能有空格)。
思路
1.写两个方法:
a.f1方法要实现:给定一个整数,将它的2的幂次方的所有幂用列表储存。如输入
137
137
137,输出
[
7
,
3
,
0
]
[7,3,0]
[7,3,0]
b.f2方法是输出函数(输出函数需要用到递归)
参考代码
def f1(x):
##获取一个数的幂
str0 = bin(int(str(x), 10))
str1 = str0[2:]
list1 = []
index = 0
for i in str1[::-1]:
if i == '1':
list1.append(index)
index += 1
list1.reverse()
return list1
def f2(list):
##格式化输出
list1 = [str(i) for i in list]
str2 = ''
for i in range(len(list1)):
if i < len(list1) - 1:
if list1[i] == "1":
str2 += "2+"
else:
if list[i] != 0:
str2 += "2({})+".format(f2(f1(list[i])))
else:
str2 += "2(0)"
if i == len(list1) - 1:
if list1[i] == "1":
str2 += "2"
else:
if list[i] != 0:
str2 += "2({})".format(f2(f1(list[i])))
else:
str2 += "2(0)"
return str2
n=int(input())
print(f2(f1(n)))