简体   繁体   中英

how can i extract last digit from input in java


import java.text.BreakIterator;
import java.util.*;
public class Main {
    public static void main(String args[]) {
       Scanner in= new Scanner(System.in);
       System.out.println("nomber");
       int n= in.nextInt();
       int s= n*n;
       int l = (""+s).length();
       System.out.println(l);


    }
}

how can I extract last digit from input in a simple way. Not so complicated like while loop.... java

Since last digit is also the remainder of dividing by 10, you can use n % 10 .

The simplest way to extract last digit is modulo to 10. Example: 123 % 10 = 3 After that, if you want to continue to extract last digit (it's 2 in this case), you should assign number = number /10 that will return the remain of the number.

// Example n = 123
int lastDigit_1 = n % 10; // This will return 3
n = n /10 // This will return 12 because 123 / 10 = 12
int lastDigit2 = n % 10; // This will return 2
n = n /10 // This will return 1
int lastDigit3 = n % 10;
... 

To implement the above concept, u should try using while loop for better approach.

Using while:

while(n != 0){
   someVariable = n % 10;
   // YOUR LOGIC HERE
   n = n / 10;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM