Results 1 to 3 of 3
 11022013, 08:11 PM #1Member
 Join Date
 Oct 2013
 Posts
 4
 Rep Power
 0
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;
}Last edited by andy_d; 11022013 at 08:17 PM.
 11022013, 08:25 PM #2
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,422
 Blog Entries
 7
 Rep Power
 28
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:
Java Code:int removeFirstDigit(int num) { if (num < 10) return num; String s= ""+num; return Integer.parseInt(s.substring(1)); }
kind regards,
JosBuild a wall around Donald Trump; I'll pay for it.
 11032013, 02:54 AM #3Member
 Join Date
 Oct 2013
 Posts
 4
 Rep Power
 0
Similar Threads

Removing a single digit from an Double
By HarleyRowland in forum New To JavaReplies: 7Last Post: 03072013, 06:43 AM 
Simple Java Help: Inverse of 4 digit Number without Strings
By mcgillstudent in forum New To JavaReplies: 7Last Post: 01282013, 09:24 PM 
Possible combinations for a n digit number???
By anishr6 in forum New To JavaReplies: 4Last Post: 05252011, 08:55 AM 
select a digit in a number
By navid in forum New To JavaReplies: 3Last Post: 12122010, 10:47 AM 
convert getValue result in a 4 digit number
By roseline43 in forum New To JavaReplies: 0Last Post: 09022008, 08:44 PM
Bookmarks