Searching...
Thursday, 8 December 2016

Algorithm and program to reverse a Number in java

23:11

This algorithm we can explain with an example, here input number=122 and expected output is 221

Reverse=0

Number=122

Formula

Until Number=0 we have to do the following
Reverse=(Reverse*10)+(Number%10)
Number=Number/10

In this example

Reverse=(Reverse*10)+(Number%10) =2
Number=Number/10= 12

Reverse=(2*10 ) + (12%10 )= 22
Number=12/10= 1

Reverse= (22*10)+ (1%10)= 221
Number=1/10=0

Java Program

package com.vinod.test;


/**
 *@authorvinodkariyathungalkumaran
 *
 */
public class ReverseNumberExample {
    public static void main(String a[]) {
        int reverse = 0;
        int number = 122;
        while (number != 0) {
            reverse = (reverse * 10) + (number % 10);
            System.out.println(reverse);
            number = number / 10;
            System.out.println(number);
        }
        System.out.println("Reversed number " + reverse);
     
        //Reversing number using StringBuilder
        StringBuilder sb=new StringBuilder(String.valueOf(122));
        System.out.println("Reversed number using StringBuilder " +sb.reverse().toString());
    }
    
    
   
}

Output

2
12
22
1
221
0
Reversed number 221
Reversed number using StringBuilder 221

 

 

 

0 comments: