Swap First and Last Digit
Problem
Read a positive integer and print the number you get when you swap its first and last digit. If the result starts with zeros, they disappear: 100 becomes 1. A number with one digit does not change.
Constraints
- 1 <= n <= 10^18
Examples
Input
1234
Output
4231
Input
100
Output
1
Solutions
We find the place value of the first digit (power). Then first = n / power, last = n % 10, and the middle digits are what is left. The result is rebuilt with the last digit in front and the first digit at the end. The original program used text and could crash for one-digit numbers.
/*
* Problem : Swap the first and the last digit.
* Input : One positive integer.
* Output : The new number.
* Approach: Use arithmetic: first = n / 10^(d-1), last = n % 10.
* Time : O(d)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
// Step 1: A number with one digit does not change.
if (number < 10) {
System.out.println(number);
return;
}
// Step 2: Find the place value of the first digit. Example: 1234 -> 1000.
long power = 1;
while (number / power >= 10) {
power = power * 10;
}
// Step 3: Take the first digit and the last digit. Example: 1234 -> first = 1, last = 4.
long first = number / power;
long last = number % 10;
// Step 4: Take the middle digits. Remove the first digit and the last digit. Example: 1234 -> 23.
long middle = (number % power) / 10;
// Step 5: Build the result: last digit, then middle digits, then first digit. Example: 4 * 1000 + 23 * 10 + 1 = 4231.
long result = last * power + middle * 10 + first;
// Step 6: Print the result.
System.out.println(result);
}
}
Hints (2)
- How do you get the first digit of a number?
- Split the number into first, middle and last part.