简体   繁体   中英

concatenating two int in java

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.

You (likely) want string concatenation (you may also want an integer result, if that is the case, see the other answers). If this is true, about the concatenation, imagine a and b are integers:

"" + a + b

This works because the + operator is overloaded if either operand is a String. It then converts the other operand to a string (if needed) and results in a new concatenated string. You could also invoke Integer.toString(a) + Integer.toString(b) or using an appropriate String.format but those methods are more long-winded.

Here is my version which works when a,b >= 0.

It is a bit longer, but is 10x faster than the log approach and 5x faster than appending strings.

int concat(int a, int b)
{
   if ( b == 0 )
      a *= 10;
   else
   {
      int tempB = b;
      while ( tempB > 0 )
      {
         tempB /= 10;
         a *= 10;
      }
   }
   return a + b;
}

Feel free to modify this to work for negative numbers.

a + "" + b

results in error "incompatible types"

// The left operand to previousOperator.
private int leftOperand;

leftOperand = leftOperand + " " + number;

number is defined as int in the method declaration

This works

import java.lang.*

leftOperand = Integer.parseInt(Integer.toString(leftOperand) + Integer.toString(number));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM