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
CodePudding user response:
Since last digit is also the remainder of dividing by 10, you can use n % 10
.
CodePudding user response:
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;
}