Write Number in Expanded Form
You will be given a number and you will need to return it as a string in Expanded Form. For example:
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0.
我的解决方案
def expanded_form(num):
num=list(str(num))
length=len(num)
i=10**(length-1)
v=0
temp=[]
while i>=1:
unit=str(int(num[v])*i)
if unit!='0':
temp.append(unit)
v+=1
i=i//10
return ' + '.join(temp)
看一下别人的
def expanded_form(num): num = list(str(num)) return ' + '.join(x + '0' * (len(num) - y - 1) for y,x in enumerate(num) if x != '0')
他这个用的是字符串的拼接法,先将数据换成列表格式,第一次取出最高位,然后加上length-1乘以0,第一个数字就算出来了,y是下标,依次递境,所以0也就会随着数字位数往后递增越来越少,外面再用join将所有的数字拼接起来。