Swap First and Last Digit of a Number in python

num = 65765  # input number
temp = num
digits = 0

# Count the number of digits
while temp > 0:
    temp //= 10
    digits += 1

if digits == 1:
    swapped_num = num  # single digit, nothing to swap
else:
    first = num // 10**(digits-1)        # first digit
    last = num % 10                       # last digit
    middle = num % 10**(digits-1) // 10  # middle part

    swapped_num = last * 10**(digits-1) + middle * 10 + first

print(swapped_num)  # Output: 52341

 

0 Comments