DilbertFan
DilbertFan

Reputation: 113

Reverse a three digit int; if there is a leading zero in the output it shoud be left out

First of all, a similar queston has already been asked here: How to calculates the number by reversing its digits, and outputs a new number

I am at the beginning of the Java trail at [Jetbrains/hyperskill][1] and the accepted [1]: https://hyperskill.org/learn/step/2217 answer to the above question is not yet taught at Jetbrains, that's why asking this question.

Here is what I have:

import java.util.Scanner;

public class Main3 {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter your number: ");
    int a = scanner.nextInt();
    int hundreds = (a % 1000) / 100;
    int tens = (a % 100) / 10;
    int ones = a % 10;
    System.out.println(ones + "" + tens + "" + hundreds);
  }
}

To be clear, if the input is 320 for instance, the output should be 23, not 023.

Just to clarify, the only subjects taught at this level is Types and variables, Naming variables, Arithmic operations, Increment and decrement, Strings, Basic literals, Printing data, Scanning the input.

Upvotes: 2

Views: 171

Answers (4)

Gulbala Salamov
Gulbala Salamov

Reputation: 308

How about getting benefit from StringBuilder?

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            StringBuilder stringBuilder = new StringBuilder(String.valueOf(scanner.nextInt())).reverse();
            if (stringBuilder.charAt(0) == '0') {
                stringBuilder.deleteCharAt(0);
            }
            System.out.println(stringBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 1

DilbertFan
DilbertFan

Reputation: 113

import java.util.Scanner;

class Main {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    var n = scanner.nextInt();
    System.out.print(n / 100 + 10 * (n / 10 % 10) + 100 * (n % 10));
    }
}

Credit for this answer goes to @OlgaAI

Upvotes: 0

you can convert the hundreds tens and ones into a integer. and print this one.

int number = 100*hundreds + 10*tens + ones;
System.out.println(number);

Upvotes: 2

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

I saw the problem and the below solution should be good to handle the cases you mentioned

public static void reverse(int num) {
        
        int rev=0;
        while(num>0) {
            int rem = num%10;
            rev=rev*10+rem;
            num/=10;
                    
            
        }
        
    System.out.println(rev);
    }

Upvotes: 1

Related Questions