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