获取一个数字的最后一位

49

我需要定义一个数字的最后一位,并将其分配给一个值。然后,返回这个最后一位。

我的代码片段没有正确工作...

代码:

public int lastDigit(int number) {
    String temp = Integer.toString(number);
    int[] guess = new int[temp.length()];
    int last = guess[temp.length() - 1];

    return last;
}

问题:

  • 如何解决这个问题?

1
为什么它不工作?你得到了错误的值还是异常? - Tomas McGuinness
1
当你创建“guess”时,你正在创建一个空数组。你需要用temp的字符填充它。正确的方法是像大多数人在下面回答的那样使用%10。但是,如果不改变方法,要修复你的代码,你可以做一些类似于Integer.parseInt(temp.substring(temp.length()-1))的事情。 - Rajesh J Advani
12个回答

169

只需返回(number % 10); 即取模。这比在字符串中进行解析和转换要快得多。

如果number可以为负数,则使用(Math.abs(number) % 10);


1
当左操作数为负数时,Java中的%运算符的语义是什么?很有可能它不会返回最后一位数字。 - Kaz
@Kaz:这是一个重要的观点:%10不能提取负数的最后一位数字。谢谢你指出来,我已经修改了。 - Bathsheba
如果数字为空怎么办? - Thermech
OP 有一个原始类型的数字:因此不能为 null。 - Bathsheba

18

以下是一种更简单的解决方案,用于获取一个 int 的最后一位数字:

public int lastDigit(int number) { return Math.abs(number) % 10; }

3
number为负数时,你可以成为第一个得到正确答案的人。 - Kaz

8
使用
int lastDigit = number % 10. 

了解取模运算: http://zh.wikipedia.org/wiki/取模运算

或者,如果您想使用字符串解决方案

String charAtLastPosition = temp.charAt(temp.length()-1);

5
不需要使用任何字符串。这会使负担过重。
int i = 124;
int last= i%10;
System.out.println(last);   //prints 4

2

不使用'%'

public int lastDigit(int no){
    int n1 = no / 10;
    n1 = no - n1 * 10;
    return n1;
}

有什么意义呢?我只看到了不必要的复杂化。 - Ole V.V.

1

你的数组没有初始化,所以它会给出默认值零。你也可以尝试这样做。

String temp = Integer.toString(urNumber);
System.out.println(temp.charAt(temp.length()-1));

1
你刚创建了一个空的整数数组。据我所知,数组guess没有包含任何内容。其余部分需要自己动手去理解和提高。

1
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;
}

0/p:

7


0

另一种有趣的方法是,它也可以允许获取不止最后一个数字:

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

0

如果您需要字符串结果,请使用StringUtils:

String last = StringUtils.right(number.toString(), 1);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接