wkwkwk
wkwkwk

Reputation: 163

How to keep only last 3 digits of an integer and be able to manipulate them?

I'm trying to write a program that would ask a user to enter an integer, keep only the last 3 digits of that input, and be able to manipulate that. For example, if they entered 1234, it would keep only 234 then it would be able to reverse those digits and output 432. Then I would want to be able to perform arithmetic on that reversed number. Thank you all for the help.

Upvotes: 0

Views: 1524

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44844

You can use the % (remainder) operator and then a StringBuilder

int val = 1234;
val = val % 1000;

System.out.println(new StringBuilder(String.valueOf(val)).reverse());

Upvotes: 2

Touch sophonara
Touch sophonara

Reputation: 80

Check I think it mayhelp you.

 String input = "1234";     //input string
 String lastFourDigits = "";     //substring containing last 3 characters
 int reversed = 0;

 if (input.length() > 3) {
    lastFourDigits = input.substring(input.length() - 3);
 } else {
    lastFourDigits = input;
 }
 Number num = Integer.parseInt(lastFourDigits);

 while(num != 0) {
        int digit = num % 10;
        reversed = reversed * 10 + digit;
        num /= 10;
 }

System.out.println("last 3 Number: " + lastFourDigits);
System.out.println("Reversed Number: " + reversed);

Upvotes: -1

Related Questions