Roman - 1 year ago 86
C++ Question

comparation of 2 binary numbers

I need to write program that will compare 2 binary numbers and return the result
I wrote this code using XOR, but idk how to improve my code, so for example 100101 and 101001 will return a < b. Can you help me fix this please?

``````string a,b;
la = a.length();
lb = b.length();

int x = 0;
if (la == lb)
{
for (int i = 0; i < la; i++)
{
if (a[i]^b[i] == 1)
{
if(a[i] > b[i])
x++;
}
else {x--;}
}
if (x > 0)
cout << a << " > " << b << endl;
if (x < 0)
cout << a << " < " << b << endl;
if (x == 0)
cout << a << " = " << b << endl;
}
``````

Guess this would be better Here no need to iterate th whole string unless they are equal. Just find the first '1' and the one which has 1 before will be bigger. As simple as that

``````int main()
{
string a,b;
cin>>a>>b;
size_t aLoc=-1,bLoc=-1;
do
{
aLoc = a.find("1",aLoc+1);
bLoc = b.find("1",bLoc+1);
if(aLoc<bLoc)
{
cout<<a<<">"<<b;
return 0;
}
else if(aLoc>bLoc)
{
cout<<a<<"<"<<b;
return 0;
}
}while(aLoc==bLoc && aLoc!=string::npos);
cout<<a<<"="<<b;
return 0;
}
``````

Edit:

aLoc give the position of 1 in first string, and bLoc for 2nd string Lets take 1 exmaple

``````a = 10111000;
``````

here first aLoc = 1 as the first '1' is at position 1

``````b = 10001100;
``````

here bLoc = 1;

now for next iteration, aLoc will be 3 as next '1' is at 3rd position

and bLoc will be 5 so naturally aLoc

which means '1' comes first in string a.

Hence

``````if(aLoc<bLoc)
a>b;
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download