Removing first digit for a number...

Hi. I'm fairly new to Java and currently reviewing for an upcoming midterm. I figured out how to do it using an array and string conversion but I feel like this may be too complicated. I'm not looking to use any built in methods etc. I'm just wondering if there is a more efficient way of doing the below.

1) I first used a while loop to get the count of digits

2) I created an array with the length of count

3) First for loop is to fill the array

4) Second for loop is get the integers from the array and concatenate into a string while ignoring the last value in the array ( which was the first digit )

5) Then parse for the integer.

It works perfectly. I'm just wondering if this can be done more efficiently.

public static int removeFirstDigit ( int n ) {

int count = 0;

String numberString = "";

int newNumber;

int temp = n;

while ( temp > 0 ) {

temp /= 10;

count++;

}

int [] digits = new int [ count ];

for ( int i = 0; i < count; i++ ) {

digits[i] = n % 10;

n /= 10;

}

for ( int i = (digits.length - 2); i >= 0; i--) {

numberString += digits[i];

}

newNumber = Integer.parseInt( numberString );

return newNumber;

}

Re: Removing first digit for a number...

Suppose a String variable 's' contains the String representation of a number; if the number is at least 10 (2 or more digits), then the following does what you want:

Code:

`int removeFirstDigit(int num) {`

if (num < 10) return num;

String s= ""+num;

return Integer.parseInt(s.substring(1));

}

I leave it to you to figure out the details.

kind regards,

Jos

Re: Removing first digit for a number...

Wow thanks! I knew I spent too much time working through that. I'll have to look into substring.