Write a program to reverse digits of a number and String

Solution 1st: Reversing digits of a number - simplest solution
https://ide.geeksforgeeks.org/w1fALxIYWU

import java.io.*;
import java.util.*;

class GFG {
    public static void main (String[] args) {
        int input, output, remainder;
        output = 0;
   
        Scanner sc = new Scanner(System.in);
        input = sc.nextInt();
   
        while(input != 0){
            remainder = input % 10;
            output = (output * 10) + remainder;
            input = input/10;
        }
   
        System.out.println(output);
    }
}

Solution 2nd: Reversing digits of a number - Out of the Box
https://ide.geeksforgeeks.org/ppy5EQjEAR

import java.lang.*;
import java.io.*;
import java.util.*;

class GFG {
    public static void main (String[] args) {
        int input;
   
        Scanner sc = new Scanner(System.in);
        input = sc.nextInt();
   
        StringBuilder strInput = new StringBuilder();
        strInput.append(input);
        strInput = strInput.reverse();
   
        System.out.println(strInput);
    }
}

Also, see:


Solution 1st: Reversing string - simplest solution
https://ide.geeksforgeeks.org/DhdX10fH82

import java.lang.*;
import java.io.*;
import java.util.*;

class GFG {
    public static void main (String[] args) {
        String input, output="";
   
        Scanner sc = new Scanner(System.in);
        input = sc.nextLine();
   
        for(int i=input.length()-1 ; i >= 0 ; i--){
            output = output + input.charAt(i);
        }

        System.out.println(output);
    }
}

Solution 1st: Reversing string - alternate solution
https://ide.geeksforgeeks.org/QPY8JQQMR7

import java.lang.*;
import java.io.*;
import java.util.*;

class GFG {
    public static void main (String[] args) {
        StringBuilder input1 = new StringBuilder();
        String input ;
   
        Scanner sc = new Scanner(System.in);
        input = sc.nextLine();
   
        input1.append(input);
        input1 = input1.reverse();

        System.out.println(input1);
    }
}

Also, see:

Comments

Post a Comment

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )