naz*_*art 32 java return digits
我需要定义一个数字的最后一位,将其赋值给value.在此之后,返回最后一位数字.
我的代码片段无法正常工作......
码:
public int lastDigit(int number) {
String temp = Integer.toString(number);
int[] guess = new int[temp.length()];
int last = guess[temp.length() - 1];
return last;
}
Run Code Online (Sandbox Code Playgroud)
题:
Ada*_*ion 15
下面是一个更简单的解决方案如何从以下位置获取最后一位数字int:
public int lastDigit(int number) { return number % 10; }
Run Code Online (Sandbox Code Playgroud)
使用
int lastDigit = number % 10.
Run Code Online (Sandbox Code Playgroud)
阅读Modulo运算符:http://en.wikipedia.org/wiki/Modulo_operation
或者,如果您想要使用您的String解决方案
String charAtLastPosition = temp.charAt(temp.length()-1);
Run Code Online (Sandbox Code Playgroud)
不需要使用任何strings。它的负担过重。
int i = 124;
int last= i%10;
System.out.println(last); //prints 4
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
114764 次 |
| 最近记录: |