编写一个返回整数

时间:2015-05-05 22:49:06

标签: java integer return modulo

我已经完成了以下任务,并且如果我可以使用字符串,则可以执行此操作 -

  

编写一个名为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;
}

任何提示?谢谢!

3 个答案:

答案 0 :(得分:2)

像这样:

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

答案 1 :(得分:0)

public static int lastDigit(int d) { 
    return Math.abs(d-((int)(d/10))*10);
}

答案 2 :(得分:0)

public static int lastDigit(int d) { 
    // using modulo
    if (d < 0) {
        return 10 - (d % 10);
    } else {
        return d % 10;
    }
}