def solve(String s) {
int zeros = 0
int nines = 0
int takeOneFromPos = s.length() - 1
while (s[takeOneFromPos] == '0' && takeOneFromPos >= 0) {
--takeOneFromPos
++zeros
}
if (takeOneFromPos == -1) return '-1'
int addOneToPos = takeOneFromPos - 1
while (s[addOneToPos] == '9' && addOneToPos >= 0) {
--addOneToPos
++nines
}
StringBuilder result = new StringBuilder()
if (addOneToPos == -1) {
result.append(1)
}
else {
result.append(s.substring(0, addOneToPos))
result.append(s[addOneToPos].toInteger() + 1)
}
result.append('0' * zeros)
result.append(s[takeOneFromPos].toInteger() - 1)
result.append('9' * nines)
return result.toString()
}
assert solve
('0050') == '0104' assert solve
('99100') == '100099'
ZGVmIHNvbHZlKFN0cmluZyBzKSB7CiAgICBpbnQgemVyb3MgPSAwCiAgICBpbnQgbmluZXMgPSAwCiAgICBpbnQgdGFrZU9uZUZyb21Qb3MgPSBzLmxlbmd0aCgpIC0gMQogICAgd2hpbGUgKHNbdGFrZU9uZUZyb21Qb3NdID09ICcwJyAmJiB0YWtlT25lRnJvbVBvcyA+PSAwKSB7CiAgICAgICAgLS10YWtlT25lRnJvbVBvcwogICAgICAgICsremVyb3MKICAgIH0KICAgIGlmICh0YWtlT25lRnJvbVBvcyA9PSAtMSkgcmV0dXJuICctMScKICAgIGludCBhZGRPbmVUb1BvcyA9IHRha2VPbmVGcm9tUG9zIC0gMQogICAgd2hpbGUgKHNbYWRkT25lVG9Qb3NdID09ICc5JyAmJiBhZGRPbmVUb1BvcyA+PSAwKSB7CiAgICAgICAgLS1hZGRPbmVUb1BvcwogICAgICAgICsrbmluZXMKICAgIH0KICAgIFN0cmluZ0J1aWxkZXIgcmVzdWx0ID0gbmV3IFN0cmluZ0J1aWxkZXIoKQogICAgaWYgKGFkZE9uZVRvUG9zID09IC0xKSB7CiAgICAgICAgcmVzdWx0LmFwcGVuZCgxKQogICAgfQogICAgZWxzZSB7CiAgICAgICAgcmVzdWx0LmFwcGVuZChzLnN1YnN0cmluZygwLCBhZGRPbmV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