开发者

how can i swap value of two variables without third one in objective c

hey guys i want your suggestion that how can change value of two variables without 3rd one. in objective cc. is there a开发者_运维技巧ny way so please inform me,


it can be done in any language. x and y are 2 variables and we want to swap them

{
  //lets say x , y are 1 ,2
  x = x + y; // 1+2 =3
  y = x - y; // 3 -2 = 1
  x = x -y; // 3-1 = 2;
}

you can use these equation in any language to achieve this


Do you mean exchange the value of two variables, as in the XOR swap algorithm? Unless you're trying to answer a pointless interview question, programming in assembly language, or competing in the IOCCC, don't bother. A good optimizing compiler will probably handle the standard tmp = a; a = b; b = tmp; better than whatever trick you might come up with.

If you are doing one of those things (or are just curious), see the Wikipedia article for more info.


As far as number is concerned you can swap numbers in any language without using the third one whether it's java, objective-C OR C/C++,

For more info

Potential Problem in "Swapping values of two variables without using a third variable"


Since this is explicitly for iPhone, you can use the ARM instruction SWP, but it's almost inconceivable why you'd want to. The complier is much, much better at this kind of optimization. If you just want to avoid the temporary variable in code, write an inline function to handle it. The compiler will optimize it away if it can be done more efficiently.


NSString * first = @"bharath"; NSString * second = @"raj";

first = [NSString stringWithFormat:@"%@%@",first,second];

NSRange needleRange = NSMakeRange(0,
                                  first.length - second.length);

second = [first substringWithRange:needleRange];

first = [first substringFromIndex:second.length];
NSLog(@"first---> %@, Second---> %@",first,second);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜