The ingenious application of the position arithmetic of the interview question

Source: Internet
Author: User
Tags arithmetic
1, judge whether a number is 2 of the n-th square
Title: Use an expression to determine whether a number x is 2 of the n-th square, that is, 2,4,8,16 ... And so on, it is not possible to use circular statements.
Parsing: 2,4,8,16 Such a number translates into binary is 10,100,1000,10000.

if x is minus 1 (the lower one and each bit of the binary is 1), this number is done with X, and if the answer is 0, then X is the n-th of the 2.


2, two number of exchanges
Title: The value of a A, a, two number is exchanged, and no intermediate variables are used.
Solution 1:
A = A+b;
b = a A;
A = a-B;
Solution 2: Use XOR or bitwise operation.
XOR operation: The same is 0, the difference is 1.
A = a^b;//a becomes a result of the same 0, which differs from 1
b = a^b;//The result and b do the operation, get the original A
A = a^b;//The result and a do the operation, get the original B

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.