Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

how to reverse a given number or string.

0 votes
asked by Shashank (48 points)
retagged by Ranjith

2 Answers

0 votes

Reversing a String

Assume that the input String that is to be reversed is stored in input. Create a new String variable reverse which hold the reversed String.  Set this variable to “” - an empty String.

Using a for loop, iterate through the character of input in reverse order. To do so, set the starting value of loop counter i to input.length()-1 and condition to i >= 0. Within the loop, extract the character at i in input using charAt() method and add that character to reverse.

At the end of the loop, you will have the reversed String in the variable reverse.

Program


import java.util.Scanner;

public class ReverseString {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter input: ");
        String input = scanner.nextLine();
        String reverse = "";
        for (int i = input.length() - 1; i >= 0; i--) {
            char ch = input.charAt(i);
            reverse = reverse + ch;
        }
        System.out.println("Reversed String = " + reverse);
    }

}

Sample Output

Enter input: java
Reversed String = avaj

Reversing a number

Take a look at this page http://www.javawithus.com/programs/reversing-a-number. Read the section titled 'Reversing a Number using Mathematical Operations'. It explains, how to reverse a number.

Program

import java.util.Scanner;

public class ReverseNumber {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = scanner.nextInt();
        int reverse = 0;
        while (num > 0) {
            int rem = num % 10;
            reverse = reverse * 10 + rem;
            num = num / 10;
        }
        System.out.println("Reversed number = " + reverse);
    }
}

Sample Output

Enter number: 3479
Reversed number = 9743

 

answered by Ranjith (2,408 points)
thank you Ranjith:)
0 votes

You could reverse the number the same way as an string. Convert the number into an string and then follow Ranjith's program, or you could directly refer to my program:

import java.util.Scanner;
 
public class ReverseNumber {
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = scanner.nextInt();
        String str= Integer.toString(num);
        String reverse="";
        for(int i=str.length()-1;i>=0;i--) {
            char ch= str.charAt(i);
            reverse=reverse+ch;
    }
    int k=Integer.parseInt(reverse);
    System.out.println(k);
}
}

 

answered by Soham Thakurata (336 points)
...