[Java, JS]-do not use the third variable to exchange two integers

Source: Internet
Author: User

Source: http://www.javaeye.com/topic/645596

 

If you do not use the third variable to exchange two integers, you may have encountered this question. For example:

JavaCode

 Public     Class  Person {

Public Static Void Main (string [] ARGs ){
// Use addition and subtraction
Int A = 10 , B = 5 ;
A
= A + B;
B
= A - B;
A
= A - B;

System. Out. println (
" A = " + A + " \ NB = " + B );
}
}

 

There is another method that is more efficient:

Java code

  Public     Class  Person {

Public Static Void Main (string [] ARGs ){
// The exchange rate is met by using a number-exclusive or equal to 0 and exclusive operations.
Int A = 10 , B = 5 ;
A
= A ^ B;
B
= A ^ B;
A
= A ^ B;

System. Out. println (
" A = " + A + " \ NB = " + B );
}
}

 

 

Of course, the above two typesAlgorithmThe corresponding js also supports the following:

JS Code

  VaR  A  =     11  , B  =    22  ;
A
= A + B;
B
= A - B;
A
= A - B;

Console. Log (
+ ' \ N ' + B)

Or

JS Code

  VaR  A  =     11  , B  =     22  ;
A
= A ^ B;
B
= A ^ B;
A
= A ^ B;

Console. Log (
+ ' \ N ' + B)

 

 

 

However, if two variables are of the object type, Java (strong type) seems powerless. But JS works. There are still many implementation methods, such:

JS Code

  VaR  A  =  {Name:  '  Jack  '  }, B  =  {Name:  '  Tom  ' };
A
= [A, B];
B
= A [ 0 ];
A
= A [ 1 ];

Console. Log (A. Name
+ ' \ N ' + B. Name)

Or

JS Code

  VaR  A  =  {Name:  '  Jack  '  }, B  =  {Name:  '  Tom  '  };
A
= {A: A, B: B };
B
= A.;
A
= A. B;

Console. Log (A. Name
+ ' \ N ' + B. Name)

 

 

It is precisely the use of JS dynamic (weak type) systems and direct object/array features. Other strong types are not allowed. The compiler will prompt a type conversion error.

Http://en.wikipedia.org/wiki/XOR_swap Resources

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.