Interview #74: Java: Reverse first and last digit of a number without converting to string

Interview #74: Java: Reverse first and last digit of a number without converting to string

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:

  • Input: A number (e.g., 12345)
  • Output: A modified number where the first and last digits are swapped (e.g., 52341)

Constraints:

  1. Do not convert the number to a string.
  2. Only swap the first and last digits, keeping other digits unchanged.


2. Steps to Solve the Problem

Extract the last digit

  • The last digit of a number num can be found using num % 10.

Extract the first digit

  • The first digit can be obtained by repeatedly dividing num by 10 until we get a single-digit number.

Find the number of digits (count)

  • This helps in reconstructing the number correctly after swapping.

Replace the first and last digit

  • Remove the last digit using integer division (num / 10).
  • Remove the first digit using modulo operation (num % (10^(count-1))).
  • Construct the new number by replacing these digits in the original structure.


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

  • lastDigit = num % 10;
  • This gives us the last digit of the number.

Extracting the first digit and counting digits

  • We use a loop to keep dividing num by 10 until only one digit is left.
  • The last remaining digit in this loop is our first digit.
  • Simultaneously, we count the number of digits.

Removing first and last digit from the middle part

  • middlePart = num % (int) Math.pow(10, count - 1); → Removes the first digit.
  • middlePart /= 10; → Removes the last digit.

Reconstructing the number

  • The last digit is placed at the highest place value (10^(count-1)).
  • The middle part remains the same.
  • The first digit is placed in the unit place.

Returning the swapped number

  • The reconstructed number is returned and printed.


5. Example Test Cases

Input 1:

Enter a number: 12345        

Processing:

  • First Digit = 1
  • Last Digit = 5
  • Middle Part = 234
  • New Number = 52341

Output 1:

Number after swapping first and last digit: 52341        

Input 2:

Enter a number: 9876        

Processing:

  • First Digit = 9
  • Last Digit = 6
  • Middle Part = 87
  • New Number = 6879

Output 2:

Number after swapping first and last digit: 6879        

Input 3 (Single Digit Case):

Enter a number: 7        

Processing:

  • Since there is only one digit, no swapping is needed.

Output 3:

Number after swapping first and last digit: 7        

6. Time Complexity Analysis

  • Extracting the first digit takes O(log N) time, where N is the input number.
  • Extracting the last digit takes O(1).
  • Removing digits and reconstructing the number takes O(1).
  • Overall, the time complexity is O(log N) (since the number of digits in N is log N in base 10).


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

  • The given problem is efficiently solved using numerical operations.
  • The approach avoids unnecessary conversions to strings, making it memory-efficient.
  • The solution works for all cases, including single-digit and multi-digit numbers.


要查看或添加评论,请登录

Software Testing Studio | WhatsApp 91-9606623245的更多文章

社区洞察

其他会员也浏览了