This problem asks you to multiply two given strings. I know the logic and I have been implementing it. The logic is to follow old school multiplication technique. While debugging my code I am stuck in a very peculiar doubt where if statement doesn't gets executed even if its condition is true.
// Example program
#include <bits/stdc++.h>
using namespace std;
string multiply(string A, string B) {
vector<string> s;
for(int i=B.size()-1; i>=0; i--){
int sum=0, carry=0;
string ans="";
for(int j=A.size()-1; j>=0; j--){
int sum = (A[j]-'0')*(B[i]-'0')+carry;
carry = sum/10;
sum = sum%10;
ans += (sum + '0');
}
if(carry>0){
ans += (carry + '0');
}
reverse(ans.begin(), ans.end());
s.push_back(ans);
}
int maxx = INT_MIN;
/*Concatenating adequate amount of zeroes to different lines */
for(int i=0; i<s.size(); i++){
int j=i;
//cout<<s[i]<<endl;
while(j--){
s[i]+="0";
}
//cout<<s[i]<<endl;
//cout<<s[i].size()<<endl;
if(maxx < s[i].size()){
cout<<"True"<<endl;
maxx=s[i].size();
}
else{
cout<<"Not true"<<endl;
}
}
/*for(int i=0; i<s.size(); i++){
cout<<s[i]<<endl;
}
cout<<maxx<<endl;
for(int i=0; i<s.size(); i++){
int x=maxx-s[i].size();
while(x--){
s[i] = "0"+s[i];
}
}
for(int i=0; i<s.size(); i++){
cout<<s[i]<<endl;
}*/
return "No answer";
}
int main()
{
string ans = multiply("1234","567");
return 0;
}
I have doubt in if statement of this part:
for(int i=0; i<s.size(); i++){
int j=i;
//cout<<s[i]<<endl;
while(j--){
s[i]+="0";
}
//cout<<s[i]<<endl;
//cout<<s[i].size()<<endl;
if(maxx < s[i].size()){
cout<<"True"<<endl;
maxx=s[i].size();
}
else{
cout<<"Not true"<<endl;
}
}
I printed s[i].size() value and maxx value just before the if statement. Initially s[i].size() is greater than maxx. But still the output printed is Not True instead of being True.
You can copy paste the code into your computer for debugging. Its completely working code.
I have been stuck on it for a long time. Kindly suggest due to what weird reason is that statement not working. Thanks in advance!