Interview #74: Java: Reverse first and last digit of a number without converting to string
Software Testing Studio | WhatsApp 91-9606623245
Looking for Job change? WhatsApp 91-9606623245
Reversing the first and last digit of a given number without converting it into a string is an interesting problem that requires understanding of numerical operations like modulus (%), division (/), and multiplication (*).
Disclaimer: For QA-Testing Jobs OR Training, WhatsApp us @ 91-9606623245
1. Approach to Solve the Problem
Given Problem Statement:
Constraints:
2. Steps to Solve the Problem
Extract the last digit
Extract the first digit
Find the number of digits (count)
Replace the first and last digit
3. Java Implementation
import java.util.Scanner;
public class SwapFirstLastDigit {
public static int swapFirstLast(int num) {
if (num < 10) { // If the number is a single digit, no swapping needed
return num;
}
int lastDigit = num % 10; // Extract last digit
int temp = num;
int count = 0;
int firstDigit = 0;
// Find the first digit and count of digits
while (temp >= 10) {
firstDigit = temp;
temp /= 10;
count++;
}
firstDigit = temp;
count++; // Total number of digits
// Remove first and last digit from the original number
int middlePart = num % (int) Math.pow(10, count - 1); // Remove first digit
middlePart /= 10; // Remove last digit
// Construct new number with swapped first and last digits
int newNum = lastDigit * (int) Math.pow(10, count - 1) + middlePart * 10 + firstDigit;
return newNum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
scanner.close();
int swappedNum = swapFirstLast(num);
System.out.println("Number after swapping first and last digit: " + swappedNum);
}
}
4. Explanation of the Code
Extracting the last digit
Extracting the first digit and counting digits
Removing first and last digit from the middle part
Reconstructing the number
Returning the swapped number
领英推荐
5. Example Test Cases
Input 1:
Enter a number: 12345
Processing:
Output 1:
Number after swapping first and last digit: 52341
Input 2:
Enter a number: 9876
Processing:
Output 2:
Number after swapping first and last digit: 6879
Input 3 (Single Digit Case):
Enter a number: 7
Processing:
Output 3:
Number after swapping first and last digit: 7
6. Time Complexity Analysis
7. Alternative Approach
If conversion to a string were allowed, a much simpler solution using character swapping could be implemented. However, since we are restricted to numerical operations, this approach efficiently solves the problem.
8. Conclusion