SPOJ BISHOP doubt

What is wrong with my code?
please help!

#include <bits/stdc++.h>
using namespace std;
void solve(string str){
	int n = str.length();
	string str1;
	int carry=0;
	for(int i=n-1;i>=0;i--){
		int a=(str[i]-'0')*2+carry;
		str1+=(char)(a%10+'0');
		carry=a/10;
		//cout<<carry<<" "<<a<<endl;
	}
	if(carry>0)
		str1+=(char)(carry+'0');
	//cout<<str1<<endl;
	carry=2;
	for(int i=0;i<str1.size();i++){
		int a=str1[i] - '0';
		if(a>1){
			str1[i]=(str1[i]- '0' - carry + 10)%10 + '0';
			break;
		//	cout<<str1[i]<<endl;
		}
		else{
			str1[i]=(str1[i]- '0' - carry + 10)%10 + '0';
			carry=1;
		}
	}
	reverse(str1.begin(),str1.end());
	bool fl=0;
	for(int i=0;i<str1.size();i++){
		if(str1[i]=='0' && fl==0)
			continue;
		cout<<str1[i];
		fl=1;
	}
	cout<<endl;
}
int main() {
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
	string str;
	while(cin>>str){
	if(str=="1" || str=="0")
		cout<<str<<endl;
	else
		solve(str);
	}
	//cout<<"Execution time : "<<tick();
      return 0;
}

Ideone link
SPOJ Link

Your code is failing on input like numbers ending with repeating 5 like these 1255.

Correct Answer is 2508

Your Code answer is 2408

Change your algorithm on these numbers.

1 Like

@neilit1992 you have made just one tiny mistake. In the subtraction procedure, you should change if(a>1) to if(a>=carry). You can surely see that the loop will break only when the carry value is subtracted from a digit >= 2. This is a bug because if at a certain index both the digit and the carry is 1, the carry will move forward to the next index instead of breaking out of the loop. Hope this helps!

2 Likes

Never thought this bug could give me, 3 WA. Thank you for tracing the bug!
Finally AC!

Thank You for the test cases.

meooow got some serious debugging skills!!

No problem :slight_smile:

//