Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating two int in java

Tags:

java

algorithm

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.

like image 367
aherlambang Avatar asked Nov 10 '10 02:11

aherlambang


2 Answers

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);
like image 141
Jeremy Avatar answered Sep 18 '22 14:09

Jeremy


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.

like image 37
Mark Elliot Avatar answered Sep 21 '22 14:09

Mark Elliot