How do I remove the first digit of an integer?
My input is an integer (for example i = 123456789).
I then want to remove the first digit, so that i equals 23456789.
How do I remove the first digit of an integer?
My input is an integer (for example i = 123456789).
I then want to remove the first digit, so that i equals 23456789.
Here's the one-line, purely numeric solution:
try this
If you want to avoid the string conversion, you can find the high digit and subtract it.
I think I remember the string-free version of this … although I totally agree with @Christian as how I would do it…
NOTE: as @Darren Gilroy pointed out, one must consider negatives and zero spocially, and my function fails to do so.
Of course
%
is a better solution also.Poor profiling attempt:
Looping the above function without the
println
for 20,000,000,000 repeats in afor
loop:The same with Christian's far-easier-to-understand and perfectly functionable version, but for only 200,000,000 repeats (because I'm lazy and got tired of waiting):
So one might argue that constructing the String objects is probably slowing it down by roughly 200×, but that isn't a really finely-tuned profiling set-up.
If you want to go for simpler methods and without using
String
, then here's my simple take:int
by10^n
.n
is the number of digits.For example
And you'd require this method:
Here is one way to do it:
String
int
Code:
Output:
Note: This can be done in one line with
Edit:
To handle negative-case, check if number is positive or integer: