我需要定义一个数字的最后一位,将其赋值给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;
}
题:
只需返回(number % 10)
;即取模数。这比解析进出字符串要快得多。
如果number
可以是负数,那么使用(Math.abs(number) % 10);
public static void main(String[] args) {
System.out.println(lastDigit(2347));
}
public static int lastDigit(int number)
{
//your code goes here.
int last = number % 10;
return last;
}
7
这是你的方法
public int lastDigit(int number)
{
//your code goes here.
int last =number%10;
return last;
}
虽然最好的方法是使用%,如果你坚持使用字符串这将起作用
public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}
但我只是为了完整而写了这个。不要使用此代码。这太可怕了。
下面是一个更简单的解决方案如何从int
获取最后一位数字:
public int lastDigit(int number) { return number % 10; }
使用
int lastDigit = number % 10.
阅读Modulo运算符:http://en.wikipedia.org/wiki/Modulo_operation
或者,如果你想使用你的String
解决方案
String charAtLastPosition = temp.charAt(temp.length()-1);
不需要使用任何strings
.Its超过负担。
int i = 124;
int last= i%10;
System.out.println(last); //prints 4
不使用'%'。
public int lastDigit(int no){
int n1 = no / 10;
n1 = no - n1 * 10;
return n1;
}
您刚刚创建了一个空整数数组。根据我的知识,数组guess
不包含任何内容。其余的你应该努力变得更好。
您的阵列没有初始化。所以它会给出默认值Zero。你也可以这样试试
String temp = Integer.toString(urNumber);
System.out.println(temp.charAt(temp.length()-1));
使用StringUtils,以防您需要字符串结果:
String last = StringUtils.right(number.toString(), 1);
另一个有趣的方法是,它还允许不仅仅是最后一个数字:
int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;
int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>
在上面的例子中,如果n为1,那么程序将返回:4
如果n为3,则程序将返回454