Question

I need to define the last digit of a number assign this to value. After this, return the last digit.

My snippet of code doesn't work correctly...

Code:

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

    return last;
}

Question:

  • How to solve this issue?
Was it helpful?

Solution

Just return (number % 10); i.e. take the modulus. This will be much faster than parsing in and out of a string.

If number can be negative then use (Math.abs(number) % 10);

OTHER TIPS

Below is a simpler solution how to get the last digit from an int:

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

Use

int lastDigit = number % 10. 

Read about Modulo operator: http://en.wikipedia.org/wiki/Modulo_operation

Or, if you want to go with your String solution

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

No need to use any strings.Its over burden.

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

You have just created an empty integer array. The array guess does not contain anything to my knowledge. The rest you should work out to get better.

Your array don't have initialization. So it will give default value Zero. You can try like this also

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

Without using '%'.

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

Use StringUtils, in case you need string result:

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

Another interesting way to do it which would also allow more than just the last number to be taken would be:

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>

In the above example if n was 1 then the program would return: 4

If n was 3 then the program would return 454

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

here is your method

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

Although the best way to do this is to use % if you insist on using strings this will work

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

but I just wrote this for completeness. Do not use this code. it is just awful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top