Reversing a decimal number
Reversing a decimal number is a favourite programming problem in the technical interviews. Below is the problem statement and the solution implemented in Java.
Problem statement
Write an optimal program to reverse the digits in a decimal number without converting it to a string. Example: 123.45 -> 54.321
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.math.BigDecimal; import java.util.Scanner; public class Solution { public static void main(String[] args) { System.out.println("*** Program to print a decimal number in reverse order ***"); System.out.println("Input a decimal number > "); try(Scanner scanner = new Scanner(System.in)){ BigDecimal num = scanner.nextBigDecimal(); // separate the integer part int integerPart = num.intValue(); // separate the decimal part BigDecimal dp = num.remainder(BigDecimal.ONE); // convert the decimal part into an integer while(dp.remainder(BigDecimal.ONE).floatValue() > 0){ dp = dp.movePointRight(1); } int decimalPart = dp.intValue(); System.out.println("Input decimal number in reverse order > "); // reverse the decimal part int remainder; while((remainder = decimalPart % 10) != 0){ System.out.print(remainder); decimalPart = decimalPart/10; } System.out.print("."); // reverse the integer part while((remainder = integerPart % 10) != 0){ System.out.print(remainder); integerPart = integerPart/10; } } } } |
Sample run
1 2 3 4 5 6 |
*** Program to print a decimal number in reverse order *** Input a decimal number > 78.23 Input decimal number in reverse order > 32.87 |
Subscribe
Login
0 Comments