Is there an easy way without having to use java library to concat two int? Maybe math?
say I have 9 and 10 , then I want it to be 910, or 224 and 225 then I want it to be 224225.
Anything in java.lang.*
should be fair game...
int a = Integer.parseInt(Integer.toString(9) + Integer.toString(10));
Addendum:
I do not like the following the syntax because the operator overloading doesn't declare intent as clearly as the above. Mainly because if the empty string is mistakenly taken out, the result is different.
int a = Integer.parseInt(9 + "" + 10);
This will give you an integer back as expected but only works when b > 0
.
int a = 224;
int b = 225;
int c = (int) Math.pow(10, Math.floor(Math.log10(b))+1)*a + b; // 224225
Just a quick explanation: This determines the number of digits in b
, then computes a multiplication factor for a
such that it would move in base 10 by one more digit than b
.
In this example, b
has 3 digits, floor(log10(b))
returns 2 (do this intuitively as 10^2=100
, 10^3 = 1000
, we're somewhere in between at 225). Then we compute a multiplication factor of 10^(2+1)
, this is 1000
. When we multiply a
by 1000 we get 224000
. Adding 224000
to 225
yields the desired 224225
.
This fails at b == 0
because log10(0)
is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With