@Sherin I believe you have misunderstood the question, as I do not believe that the initial input for the problem was ever intended to be a string of binary digits but rather I think the original op was interested in manipulation of integers at the binary level. We can never know for sure since the question is 7 years old and I doubt the OP is coming back.
However looking at your solution for having 2 strings of binary digits then here are a few comments
-
for(int i=0;s1[i]!='\0';i++)
-
{
-
n=n+1;
-
}
You are trying to calculate the number of characters in the string; however std::string does not store a '\0' terminator in its strings (or at least there is no requirement in the standard to do that). If you want to iterate through every character of a string then use an iterator
-
for(auto iter = s1.begin(); iter != s1.end(); ++iter)
-
...
If you really need to have the index of the character then the correct stop condition is the length of the string not the value of the last character
-
for(int i=0; i < s1.length(); i++)
-
...
Talking of which your code is just calculating the length so just call
s1.length()
.
-
for(int i=n-1;i>=0;i--)
-
{
-
q=s1[i]-48;
-
k=k+pow(2,n-1-(i))*q;
-
}
You are calculating the value of the string as an integer. Firstly you have a magic number, 48, that means your code is assuming that the execution character set is ASCII. If you want to subtract the value of the character '0' then subtract the value of the character '0' without making any assumptions about what character encoding is in use
q=s1[i]-'0';
.
Worst this is complex and inefficient due to all those unnecessary calls to pow; the pseudo code to convert a string of digits in base N into an integer does not need to call pow and looks something like this
-
string text // a string of digits in base N
-
integer base // The base, N, of the string of digits
-
integer result = 0
-
-
foreach digit in text // Note strings are read left to right
-
// so we get the most significant digit first
-
result = result * base // Another digit so multiply by the number base
-
result = result + digit - '0' // Add the value of this digit
No need for any calls to pow or to know the length of the string ahead of time although you may wish to check that
- All the the characters in the string are valid for the base
- There aren't so many digits in the string that you will cause overflow in the integer
Finally if this really was what was required then you can just call standard library function
int std::stoi (const string& str, size_t* idx = 0, int base = 10);
Reducing the entire program to
-
#include<string>
-
#include<iostream>
-
using namespace std;
-
-
int main() {
-
int t;
-
cin>>t;
-
while(t>0)
-
{
-
string s1,s2;
-
cin>>s1;
-
cin>>s2;
-
int k=stoi (s1, nullptr, 2);
-
int l=stoi (s2, nullptr, 2);
-
cout<<l*k<<endl;
-
-
t=t-1;
-
}
-
return 0;
-
}
Although that code could bear having some error checking added.