0

I'm given the following task, and can do it if I can use a string-

Write a method named lastDigit that returns the last digit of an integer. For example, lastDigit(3572) should return 2. It should work for negative numbers as well. For example, lastDigit(-947) should return 7.

Where this problem gets tricky for me is that I am not allowed to use a String to solve this problem. Here's what I have thus far-

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

Any tips? Thanks!

user1803551
  • 12,965
  • 5
  • 47
  • 74
vhbravo
  • 9
  • 1
  • 1
  • 2

3 Answers3

2

Like this:

public static int lastDigit(int d) { 
     return Math.abs(d % 10);
}
Kevin Walker
  • 116
  • 4
  • This won't work for negative numbers. – mrQWERTY May 05 '15 at 23:14
  • @Renren29: Actually, it will work with negatives just fine. That's why there is a Math.abs. – Kevin Walker May 05 '15 at 23:17
  • Have you tried putting in -9 for d? – mrQWERTY May 05 '15 at 23:52
  • However, I'm confused why this works. Normally, -9 % 10 evaluates to 1, and then abs is applied to it...which should yield 1. However, I just ran this code and it produces 9. Which confuses me. – mrQWERTY May 06 '15 at 00:06
  • 1
    @Renren29 The `%` operator in Java will return negatives. `m % n` will have a result `x` such that `-m < x < m`. So `-9 % 10` will return `-9`; `Math.abs(-9)` is trivially 9. – M. Shaw May 06 '15 at 00:09
0
public static int lastDigit(int d) { 
    return Math.abs(d-((int)(d/10))*10);
}
Alan Zeng
  • 74
  • 1
  • 7
  • This works, thank you! But can you explain what d/10 * 10 does exactly? – vhbravo May 05 '15 at 22:56
  • 1
    @vhbravo This is not the best way. The comments guided you to the correct way to do it (modulus). – user1803551 May 05 '15 at 22:57
  • 1
    @vhbravo, for example (int)24/10 becomes 2, multiply 2 by 10 becomes 20. The last digit is zeroed out, basically. But using modulo is a better approach. – Alan Zeng May 05 '15 at 23:02
0
public static int lastDigit(int d) { 
    // using modulo
    if (d < 0) {
        return 10 - (d % 10);
    } else {
        return d % 10;
    }
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
Alan Zeng
  • 74
  • 1
  • 7