First And Last Digit Swap Algorithm
2 min readMay 25, 2023
ALGORITHM:
- Get the input number
n
. - Initialize
count
as 0. This variable will be used to determine the number of digits in the input number. - Initialize
lastdigit
,firstdigit
,remaining
, andswapnum
variables. - Repeat the following steps until
n
is greater than 0:
- Divide
n
by 10 (n = n / 10
). - Increment
count
by 1 (count = count + 1
).
- To find the
swapnum
, we need to separate the first and last digits of the number and swap them. Follow these steps:
- Get the last digit of the number by taking the remainder when divided by 10 (
lastdigit = n % 10
). - To find the first digit, divide
n
by 10 raised to the power of (count - 1
) (firstdigit = n / 10^(count - 1)
). - Calculate the remaining digits by taking the remainder when divided by 10 raised to the power of (
count - 1
) (remaining = n % 10^(count - 1)
). - Calculate the
swapnum
using the formula:swapnum = lastdigit * 10^(count - 1) + remaining - lastdigit
. - Add the first digit to the
swapnum
(swapnum = swapnum + firstdigit
).
6.Print the swapnum
.
CONCLUSION:
The algorithm aims to swap the first and last digits of the input number.
It accomplishes this by first counting the number of digits in the input number (count
). Then, it separates the first and last digits, calculates the remaining digits, and constructs the swapped number (swapnum
).
Finally, it prints the swapnum
.
FLOWCHART: