简体   繁体   English

我如何从 java 中的输入中提取最后一位数字

[英]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不像 while 循环那么复杂.... java

Since last digit is also the remainder of dividing by 10, you can use n % 10 .由于最后一位也是除以 10 的余数,您可以使用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.提取最后一位数字的最简单方法是对 10 取模。示例:123 % 10 = 3 之后,如果您想继续提取最后一位数字(在本例中为 2),您应该分配 number = number /10 将返回剩下的号码。

// 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.要实现上述概念,您应该尝试使用 while 循环以获得更好的方法。

Using while:使用时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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