(written question) the number of binary 1 is the same as the decimal distance

Source: Internet
Author: User
Title: input: Integer a output: integer b Condition: A and B are the same number of binary 1, and the distance between A and B | a-b| minimum. Ideas:

According to test instructions, the number of binary 1 of a and B is the same and requires a minimum distance, then the difference between A and B lies in the adjacent bit bits, such as 1100 and 1010,0011 and 0101.

When the last digit of a (low) is 0, the last (right) one is found 1, then the 1 is exchanged with the 0 on the left, i.e., 1100 and 1010

When the last digit of a (low) is 1, the last (right) one is found 0, then the 0 is exchanged with the 1 on the right, which means B is obtained. such as 0011 and 0101

Code:
#include <iostream>using namespace Std;int samesumofone (int a) {    if (a==0)        return 0;    int b=0;    int pos=0;    if ((a&1) ==0) {        while ((((A>>pos) &1) ==0)            pos++;        b=a-(1<<pos) + (1<< (pos-1));    }    else{        while (((A>>pos) &1) ==1)            pos++;        b=a-(1<< (pos-1)) + (1<<pos);    }    return b;} int main () {    int a[]={0,1,2,3,4,5,6,7,8,9,10};    int n=sizeof (a)/sizeof (a[0]);    for (int i=0;i<n;i++)        cout<<a[i]<< "" <<samesumofone (A[i]) <<endl;    cout<<endl;    return 0;}
Operation Result:

(written question) the number of binary 1 is the same as the decimal distance

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.