我给出了以下任务,如果我可以使用字符串 -
,可以做到这一点写一个名为
lastDigit
的方法,该方法返回整数的最后一个数字。例如,lastDigit(3572)
应返回2
。它也应该为负数工作。例如,lastDigit(-947)
应返回7
。
这个问题对我来说很棘手的是,我不允许使用String
来解决此问题。这是我到目前为止所拥有的 -
public static int lastDigit(int d) { // d is the integer they call
// i know that whatever goes here will be something like this
int b = charAt(length - 1);
return b;
}
有什么提示吗?谢谢!
这样:
public static int lastDigit(int d) {
return Math.abs(d % 10);
}
public static int lastDigit(int d) {
return Math.abs(d-((int)(d/10))*10);
}
public static int lastDigit(int d) {
// using modulo
if (d < 0) {
return 10 - (d % 10);
} else {
return d % 10;
}
}