I want to print the digits of an integer in order, and I don't want to convert to string. I was trying to find the number of digits in given integer input and then divide the number to 10 ** (count-1), so for example 1234 becomes 1.234 and I can print out the "1". now when I want to move to second digit it gets confusing. Here is my code so far: Note: Please consider that I can only work with integers and I am not allowed to use string and string operations.
def get_number():
while True:
try:
a = int(input("Enter a number: "))
return a
except:
print("\nInvalid input. Try again. ")
def digit_counter(a):
count=0
while a > 0:
count = count 1
a = a // 10
return count
def digit_printer(a, count):
while a != 0:
print (a // (10 ** (count-1)))
a = a // 10
a = get_number()
count = digit_counter(a)
digit_printer(a, count)
I want the output for an integer like 1234 as below:
1
2
3
4
CodePudding user response:
Using modulo to collect the digits in reversed order and then print them out:
n = 1234
digits = []
while n > 0:
digits.append(n)
n //=10
for i in reversed(digits):
print(i)
Recursive tricks:
def rec(n):
if n > 0:
rec(n//10)
print(n)
rec(1234)
CodePudding user response:
Finding the largest power of 10 needed, then going back down:
n = 1234
d = 1
while d * 10 <= n:
d *= 10
while d:
print(n // d % 10)
d //= 10
CodePudding user response:
You can do in this way -
def reverse_number():
num = int(input("Enter a number: "))
# Reverse start here
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 digit
num //= 10
# Reverse end here
return reversed_num
print(reverse_number())