Friday, 16 October 2015

Write a program to reverse a number in java

Reversing a Number 
We will see three different ways of reversing a number.

Reversing a Number using Mathematical Operations
Let the input number be n. We initialize the result to zero. When the program finishes execution, result will contain the reversed number. We extract the digits of the number starting from the right one by one and add it to the result. The extracted digit would be removed from the original number. This task needs to be performed repeatedly until no more digits are left in the original number.
 Since this task is repetitive in nature, we use a while number with the loop condition being n > 0, where n is the input number. The last digit of n can is the same as the remainder obtained on
dividing the number by 10. We use the modulo operator for this purpose. To remove the
extracted number
 from n, we divide n by 10. Note that since both n and the number we are dividing with (10)
 are int values, the resulting value will be an int and not a decimal. The final step is to add the extracted
digit to the result. This can be done by multiplying the result with 10 and adding the extracted
digit to it.To illustrate the above steps, let us take an example where a particular iteration n
is 97 and the result till that point of time is 34. 97 % 10 gives 7 ( rem ). Diving n (97) by
10 makes it 9. And finally, adding 7 to the result gives 34*10+7=347.

Given below is a method which takes an integer parameter n, reverses it and returns the result. 

public void reverse(int n) {
   int result = 0;
   int rem;
   while (n > 0) {
       rem = n % 10;
       n = n / 10;
       result = result * 10 + rem;
   }
}

Here is a complete program which takes an integer input from the user and displays the reversed number on the screen. 

public class ReverseNumber {

   public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
       System.out.print("Enter the number to be reversed : ");
       int input = s.nextInt();
       int result = reverse(input);
       System.out.println("The reversed number is " + result);
   }

   public static int reverse(int n) {
       int result = 0;
       int rem;
       while (n > 0) {
           rem = n % 10;
           n = n / 10;
           result = result * 10 + rem;
       }
       return result;
   }
}

Here is a sample execution.

Enter the number to be reversed : 347
The reversed number is 743

Reversing a Number using String operations 
To reverse a number using String operations, we first convert the int value to a String using the
static method, valueOf(int) of the String class. Next, we extract the characters of the String
from the right, one by one and append it to the result, which in the beginning of the program
would be initialised to an empty String. Finally, the reversed String can be converted back
to an int using the parseInt(String) method of Integer class.

Here is a method implementing the above procedure.

public static int reverse(int n) {
   String input = String.valueOf(n);
   String result = "";
   for (int i = input.length() - 1; i >= 0; i--) {
       result = result + input.charAt(i);
   }
   int reversedInt = Integer.parseInt(result);
   return reversedInt;
}

Reversing a Number using StringBuilder 
In the previous method, we have reversed the String manually by reading the characters from
 right to left and adding them in that order to the result String. This reversing operation can be
 done in more convenient way by using the StringBuffer class and its method reverse(). 
We first construct a String using the input integer. A StringBuffer object is then constructed
 using the String. These two steps can be combined into a single step in the following way: 

StringBuffer s = new StringBuffer(n+"");

However, the following statement will give incorrect results.

StringBuffer s = new StringBuffer(n);

This is because the constructor of StringBuffer requires a String as its input from which the StringBuffer is to be constructed. If an integer is passed as an input, that integer would be taken
as the initial length of the StringBuffer.

The integer n concatenated with an empty String results in a String which is passed to the constructor of StringBuffer. The reverse() process is then invoked on the StringBuffer object which will reverse its contents. Now, the StringBuffer is converted back to a String and then to an int using toString() and parseInt() methods respectively.

We can also use the StringBuilder class instead of the StringBuffer class. The difference between these two classes is that StringBuffer is synchronised while StringBuilder is not.

Here is the complete method illustrating the above procedure. 

public static int reverse(int n) {
   String inputString = String.valueOf(n);
   StringBuffer stringBuffer = new StringBuffer(inputString);
   stringBuffer.reverse();
   String reversedString = stringBuffer.toString();
   int reversedInt = Integer.parseInt(reversedString);
   return reversedInt;
}

How to Swap Two Numbers without Temp or Third variable in Java

In this post we will explain two methods to swap the value of two variables.

Method 1: swapping two numbers using a third (temp) variable
Method 2: swapping two numbers without a temp variable.
We can swap two variables using a third or temporary variable with the use of 
three assignment statements.
The basic technique is to store in the temp variable the value of one of the two 
variables to swap. If the two variables are A and B, we must follow this steps to swap them:
Step 1: The value of the variable A is stored in the temp variable
temp = A;
Step 2: Once the value of A is stored, we can store in A the value of B
A = B;
Step 3: And finally the initial value of A (temp) is stored in B:
B = temp;
For example,
A = 1
B = 2
A
B
1
2
-
1
2
1
2
2
1
2
1
1
The logic to swap two variables using a third variable is the same for all the 
programming languages. It also can be done by first storing the value of B.
temp = B;
B = A;
A = temp;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int A, B, temp;
        System.out.print("Enter an integer value for A: ");
        A = input.nextInt();
        System.out.print("Enter an integer value for  B: ");
        B = input.nextInt();
        System.out.println("Before: A = " + A + "   B = " + B);
      
        temp = A;
        A = B;
        B = temp;
       
        System.out.println("After: A = " + A + "   B = " + B);
    }
}
Output:
Enter an integer value for A: 1
Enter an integer value for  B: 2
Before: A = 1   B = 2
After: A = 2   B = 1
2. Java program to swap two numbers without using a temp variable.
We can do it by performing arithmetic operations.
If the two variables are A and B, we can perform one addition followed by two
 subtractions:
A = A + B;
B = A – B;
A = A – B;
For example,
A = 2
B = 3
A
B
2
3
5
3
5
2
3
2
We can also do it by performing one multiplication followed by two divisions:
A = A * B;
B = A / B;
A = A / B;
A
B
2
3
6
3
6
2
3
2
Here is the complete Java code using the addition-subtraction method:
import java.util.Scanner;
public class JavaApplication360 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int A, B;
        System.out.print("Enter an integer value for A: ");
        A = input.nextInt();
        System.out.print("Enter an integer value for  B: ");
        B = input.nextInt();
        System.out.println("Before: A = " + A + "   B = " + B);
        A = A + B;
        B = A - B;
        A = A - B;
        System.out.println("After: A = " + A + "   B = " + B);
    }
}
Enter an integer value for A: 2
Enter an integer value for  B: 3
Before: A = 2   B = 3
After: A = 3   B = 2