My code long but easy to understand in c++


#1
string Solution::solve(string str) {
int n = str.length();
if(n == 1) {
	if(str[0] == '9') {
		str = "11";
	} 
	else {
		str[0]++;
	}
	return str;
}
if(n%2 != 0) {
	int mid = n/2;
	int l = mid-1, r=mid+1;
	while(true) {
		if(str[l] > str[r]) {
			str[r] = str[l];
			break;
		}
		else if(str[l] < str[r]) {
			int i = 0;
			int carry = 1;
			while(mid-i >= 0 && carry) {
				// cout << i;
				if(str[mid-i] == '9') {
					str[mid-i] = '0';
					carry = 1;
				}
				else {
					str[mid-i]++;
					carry = 0;
				}
				i++;
			}
			// cout << str;
			break;
		}
		else {
			l--;
			r++;
			if(l == -1 ) {
				// no. is palidrome increment mid val by 1
				int i = 0;
				int carry = 1;
				while(mid-i >= 0 && carry) {
					if(str[mid-i] == '9') {
						str[mid-i] = '0';
						carry = 1;
					}
					else {
						str[mid-i]++;
						carry = 0;
					}
					i++;
				}
				if(str[0] == '0') {
					str[0] = '1';
					str += '1';
				}
				break;
			}
		}
	}
	for(int i=0; i<str.length()/2; ++i) {
		str[str.length()-i-1] = str[i];
	}

// cout << str;
}
// even cases
else {
int mid = n/2;
int l = mid-1, r = mid;
while(true) {
if(str[l] > str[r]) {
str[r] = str[l];
// cout << str;
break;
}
else if(str[l] < str[r]) {
str[l]++;
// cout << str;
break;
}
else {
l–;
r++;
if(l == -1) {
int i = 1;
int carry = 1;
while(carry && mid-i >= 0) {
if(str[mid-i] == ‘9’) {
str[mid-i] = ‘0’; // 999999
carry = 1;
}
else {
carry = 0;
str[mid-i]++;
}
i++;
}
// cout << str << endl;
if(str[0] == ‘0’) {
str[0] = ‘1’;
str[mid] = ‘0’;
str += ‘1’;
}
break;
}
}
}
for(int i=0; i<str.length()/2; ++i) {
str[str.length()-i-1] = str[i];
}
// cout << str;

}
return str;

}