views:

217

answers:

5

Hello, sorry for my bad title (and noob question), but how can I add two numbers like 7 and 6 and the result should be 76. Is there a operation symbol in objective-c?

Thanks and sorry for my bad English.

+2  A: 

That's not a numeric operation, it's string concatenation.

http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings-in-objective-c

ceejayoz
+3  A: 

There is no built in symbol to concatenate numbers. However, you can accomplish this by doing:

int first; /* Assuming this is initialized to the first number */
int second; /* Assuming this is initalized to the second number */
int myVal = [[NSString stringWithFormat:@"%d%d",first, second] intValue];
Mike
Parsing format strings is expensive. Use -stringByAppendingString: when you can.
NSResponder
That would require two separate memory allocations, which could be more expensive than parsing this (simple) format expression string. At any rate, I don't think the performance of either method will be a huge issue.
Mike
Agreed here with Mike. The complexity of setting up two strings from integers and concatenating them is unlikely to be better than the +stringWithFormat for this problem. It would certainly require profiling to know for certain, since the other common way, using NSNumber -stringValue, could be even more expensive. Even if you already had the strings, I'd be very curious of the actual cost of +stringWithFormat versus -stringByAppendingString, especially in the case of more than 2 elements, and only profiling would tell us. Cocoa makes no promises about efficiency in either case.
Rob Napier
+2  A: 

FirstNum * 10 + secondNum :-)

Matt
That will only work for one-digit numbers.
Mike
+1  A: 

If you want two numbers x and y to add to xy, you can do

10*x + y.

For 7 and 6

7*10 + 6 = 76

jkeesh
That will only work for one-digit numbers.
Mike
A: 

Hi, I don't know much about objective-c but I would say:

  • If you get the numbers from an array, like nums= array(7,6), initialize result= 0 and then do a foreach on them. For each value you find, do : res= res*10 + value. At the end, even if you got 7 numbers to concatenate you'll get the result right. ie:

    Array nums= Array(7,6,8,9); int res= 0; int value; foreach (value in nums) res= res*10 + value;

  • If you can use strings, just concatenate them like suggested above. there is probably a function to concatenate all values from an array as well to make it flexible.

Hope it helps

C^

acerb