avocadoLambda
avocadoLambda

Reputation: 1046

How to calculates the number by reversing its digits, and outputs a new number

I am trying to write a code that reads a three-digit number, calculates the new number by reversing its digits, and outputs a new number. I used Scanner. If there is a "0" at the beginning of the number then it should not appear

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int unity = (a%10)/100;
        int tens = (a%100)/10;
        int hundreds = a/100;

        System.out.println(unity+""+tens+""+hundreds);
    }
}

What's wrong with my code?

Upvotes: 0

Views: 312

Answers (3)

ShaliniCodes
ShaliniCodes

Reputation: 59

The problem with your code is that you are concatenating and printing the output as string. You can add if statements:

if(unity == 0)
  System.out.println(tens+""+hundreds);

Similarly an if statement for tens. By doing this you can skip zeros being printed. You can also try this:

int result = (unity*100) + (tens*10) + hundreds;
System.out.println(result);

You can also go one more step ahead and write a recursive function to solve this.

Upvotes: 3

Julien Maret
Julien Maret

Reputation: 589

Try this:

int unity = a%10;
int tens = parseInt(a%100/10);
int hundreds = parseInt(a/100);

Upvotes: 0

amrtaweel
amrtaweel

Reputation: 96

Try this code

Scanner scanner = new Scanner(System.in);
int a= scanner.nextInt();
String n=String.valueOf(a);
       n=new StringBuilder(n).reverse().toString();
       int end=Integer.parseInt(n);
System.out.println(end);

Upvotes: 4

Related Questions