Take input number from the user and print its reverse.
从用户处获取输入号码并打印其反面。
Example:
例:
Input:
12345
Output:
54321
Here, we are implementing program to reversing a given number using 2 different ways.
在这里,我们正在实施程序,以使用2种不同的方式来反转给定的数字 。
1) Famous approach for reversing the number: Take input from the user and typecast into an integer, then iterate in the loop till num is not become zero, inside the loop:
1) 逆转数字的著名方法 :从用户输入并将其类型转换为整数,然后在循环中循环直到num在循环内不为零:
Find out the remainder.
找出其余的。
Using this: rev_num = rev_num * 10 + remainder.
使用这个:rev_num = rev_num * 10 +余数。
Update that number by diving by 10.
通过跳水10来更新该数字。
After coming out of the loop printing the reverse number.
退出循环后,打印反向编号。
if __name__ == "__main__" :
# take string input from user
num = int(input('Enter a number: '))
rev_num = 0
# iterate the loop till num is not equal to zero
while(num) :
rem = num % 10
rev_num = rev_num* 10 + rem
num //= 10
print('Reverse number is: ', rev_num)
Output
输出量
Enter a number: 12345
Reverse number is: 54321
2) Make a user-defined function for reversing the Number: Take input from the user and typecast into integer, thenreverseNum() function call.
2) 制作一个用于反转Number的用户定义函数 :从用户那里输入输入并将其类型转换为整数,然后调用verseNum()函数。
Inside the function:
函数内部:
Iterate in the loop till num does not become zero:
在循环中迭代,直到num不为零:
Find out the remainder.
找出其余的。
Using this: rev_num = rev_num * 10 + remainder.
使用这个:rev_num = rev_num * 10 +余数。
Update that number by diving by 10.
通过跳水10来更新该数字。
After coming out of the loop returning the reverse number to the main.
退出循环后,将反向编号返回到主编号。
# define a function for finding
# reverse of the number
def reverseNum(num) :
rev_num = 0
# iterate the loop till num is not equal to zero
while(num) :
rem = num % 10
rev_num = rev_num* 10 + rem
num //= 10
return rev_num
# Main() method
if __name__ == "__main__" :
# take string input from user
num = int(input('Enter a number: '))
print('Reverse number is: ', reverseNum(num))
Output
输出量
Enter a number: 12345
Reverse number is: 54321
翻译自: https://www.includehelp.com/python/program-to-reverse-a-given-number-2-different-ways.aspx