Swap First and Last Digit of a Number in JavaIn this section, we will learn how to swap first and last digit of a number. Step 1: Read the integer input from the user. The first step is to read an integer input from the user. We can use the Scanner class to achieve this. Here's a snippet of code to read the input. Code creates a Scanner object to take input from the user, prompts the user to enter an integer, and stores it in the variable number. Step 2: Extract the first and last digits. To swap the first and last digits, we need to extract these digits from the number. We can do this by using mathematical operations. Step 3: Remove the First and Last Digits. Now that we have extracted the first and last digits, we need to remove them from the original number. We can achieve this by dividing and then multiplying by powers of 10 Step 4: Print the new number with swapped digits. SwapDigits.java Output: Enter any number of two or more digits: 15489 95481 Time complexity Reading Input: Reading an integer from the user using in.nextInt() takes O(1) time as it's a single input operation. Calculations in the main() method: The while loop that calculates the number of digits in the input number (k) iterates log10(x) times because it repeatedly divides z by 10 until z becomes 0. Therefore, this part has a time complexity of O(log10(x)). Other mathematical operations such as calculating num1, num2, num3, and num4 involve basic arithmetic operations and exponentiation (pow), which have constant time complexities with respect to the size of the input number. So, these operations can be considered O(1). Overall, the time complexity of this code is O(log10(x)), where x is the input number. Space Complexity Memory for the integer variables (x, z, k, i, num1, num2, num3, and num4) are all integers, so they each consume a constant amount of memory, which is O(1). The Scanner object (in) consumes a small amount of memory for handling input, but this memory usage doesn't depend on the size of the input number, so it can also be considered O(1). Therefore, the overall space complexity of this code is O(1), as it uses a constant amount of memory regardless of the size of the input number. Swap First and Last Digit of a Number Without Using Loop.SwapDigits.java Output: Enter any number of two or more digits: 15489 95481 Next TopicAdapter Design Pattern in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India