获取数字的最后一位数字

问题描述 投票:31回答:12

我需要定义一个数字的最后一位,将其赋值给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;
}

题:

  • 如何解决这个问题?
java return digits
12个回答
132
投票

只需返回(number % 10);即取模数。这比解析进出字符串要快得多。

如果number可以是负数,那么使用(Math.abs(number) % 10);


0
投票
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
投票

这是你的方法

public int lastDigit(int number)
{
    //your code goes here. 
    int last =number%10;
    return last;
}

-1
投票

虽然最好的方法是使用%,如果你坚持使用字符串这将起作用

public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}

但我只是为了完整而写了这个。不要使用此代码。这太可怕了。


15
投票

下面是一个更简单的解决方案如何从int获取最后一位数字:

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

7
投票

使用

int lastDigit = number % 10. 

阅读Modulo运算符:http://en.wikipedia.org/wiki/Modulo_operation

或者,如果你想使用你的String解决方案

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

4
投票

不需要使用任何strings.Its超过负担。

int i = 124;
int last= i%10;
System.out.println(last);   //prints 4

1
投票

不使用'%'。

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

0
投票

您刚刚创建了一个空整数数组。根据我的知识,数组guess不包含任何内容。其余的你应该努力变得更好。


0
投票

您的阵列没有初始化。所以它会给出默认值Zero。你也可以这样试试

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

0
投票

使用StringUtils,以防您需要字符串结果:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.