vorcorur
vorcorur

Reputation: 13

Returning the last digit of every number in an array

My problem is that I'm trying to return the last digit of every element in an int array but the function below rather returns the last element of the array. How would I go about doing this.

Array: {10, 12, 41, 23, 71}

Expected output: 0, 2, 1, 3, 1

public class TestForEachLoop
{
    private int[] iLoop = new int[5];
    
    public int getLastDigit(){

        int[] iLoop = new int[]{10, 12, 41, 23, 71};
        int lastnumber = iLoop[iLoop.length - 1];
        return lastnumber;
    }    
}

Upvotes: 0

Views: 2188

Answers (4)

lester-barahona
lester-barahona

Reputation: 46

public int getLastDigit(int number){
    String sNumber=Integer.toString(number);
    return Integer.parseInt(String.valueOf(sNumber.charAt(sNumber.length() - 1))); //parseInt only accept String value
}

public int[] getVectorLastNumbers(int[] numbers){
    int[] lastNumbers=new int[numbers.length];
    for(int i=0;i<numbers.length;i++){
     lastNumbers[i]=getLastDigit(numbers[i]);  
    }
   return lastNumbers;
}

Upvotes: -1

dreamcrash
dreamcrash

Reputation: 51443

You can retrieve the last digit of a number by using the modulus '%' operation (more about it here) combined with Math.abs() to avoid getting into problems with negative numbers. Then you just need to apply that logic to each element of your array.

You can do it with streams from Java 8 very nicely:

  int[] iLoop = new int[]{10, 12, 41, 23, 71};
  Arrays.stream(iLoop).forEach(n -> System.out.print(Math.abs(n) % 10 + " "));

with a running example:

import java.util.Arrays;
class Main {  
  public static void main(String args[]) { 
      
      int[] iLoop = new int[]{10, 12, 41, 23, 71};
      Arrays.stream(iLoop).forEach(n -> System.out.print(Math.abs(n) % 10 + " "));
  } 
}

Upvotes: 0

WJS
WJS

Reputation: 40034

You need to use a for loop to iterate over the array.

for (int i = 0; i < array.length; i++ ) {
   // do something with array[i]
}

To get the last digit of each number, you should use the remainder % operator. For two numbers m and n, m % n returns the remainder of m divided by n. Beware of the negative numbers you might need to use Math.abs() as well.

Upvotes: 2

ABC
ABC

Reputation: 655

You can use modulo operator to get the last digit of a number and then use the abs method in the Math class to get the positive value.

public class Main {
    
    public static int getLastDigit(int n){
        int lastDigit = Math.abs(n % 10);
        return lastDigit;
    }
    
    public static void main(String[] args){
        int[] iLoop = new int[]{10, 12, 41, 23, 71};
        for(int i = 0; i < iLoop.length; i++){
            System.out.print(getLastDigit(iLoop[i]) + " ");
        }
    }
}

Upvotes: 1

Related Questions