Swapping of two numbers without using a third variable


/ Published in: ActionScript 3
Save to your folder(s)

Looking forward for the most optimized solution for the same


Copy this code and paste it in your HTML
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
  3. <mx:Script>
  4. <![CDATA[
  5. public function init():void{
  6. var a:Number = 5;
  7. var b:Number = 6;
  8.  
  9. // solution 2 : using xor
  10. a = a^b; // a = 1^2 = 1
  11. b = a^b; // b = 1^2 = 1
  12. a = a^b; // a = 1^1 = 1
  13. txt.text ="\n XOR Method >>> a: "+a+" b: "+b;
  14.  
  15. // solution 1
  16. a=a+b; // a = 1+2 = 3
  17. b=a-b; // b = a-b = 3-2 = 1
  18. a=a-b; // a = 3-1 = 2
  19. txt.text += "\n Solution 1 >>> a: "+a+" b: "+b;
  20.  
  21. // solution 3
  22. a=a*b;
  23. b=a/b;
  24. a=a/b;
  25. txt.text +="\n Solution 3 >>> a: "+a+" b: "+b;
  26. }
  27. ]]>
  28. </mx:Script>
  29. <mx:TextArea x="118" y="57" width="553" height="412" id="txt"/>
  30. </mx:Application>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.