輸入123456,輸出654321,兩個都是int類型;blog
輸入的參數爲num/out,int類型;rem
返回值爲int類型。it
第一種:(傳入的值爲正整數)【若是是負數或者爲零呢?】class
out = 0 while num: out = out * 10 + num % 10 num /= 10 return out
第二種(考慮了正負數、爲零的狀況):di
out = 0 is_negative = False if num < 0: is_negative = True # is_negative = "negative" if num < 0 else "positive" num = abs(num) while num: out = out * 10 + num % 10 num /= 10 if is_negative: return -out else: return out
最初的寫法(不考慮任何狀況):while
def reserve_num(num): remainder = 0 remainder = num %10 while num>1: num /= 10 if num > 0: remainder = remainder*10 + num %10 return remainder
運行結果:return
if __name__ == '__main__': print reserve_num(543211) #輸出112345