https://www.codechef.com/viewsolution/28366024
i dont understand why i got a TLE for the above solution!Someone please explain.
https://www.codechef.com/viewsolution/28366024
i dont understand why i got a TLE for the above solution!Someone please explain.
@kaiyu Defect is here:
unsigned int diff = a.length() - b.length();
When b.length()
is greater than a.length()
then it’s trying to assign negative value into a unsigned
variable BUT it’s impossible, that’s why the variable diff
holds a large garbage value something like this:
Therefor a large loop and TLE
...
else if(b.length()>a.length()) {
for (int i = 0; i < diff; ++i) { // large loop - hence TLE
a='0'+a;
}
}
Enjoy coding
ohhh!
Thank youu for your help.
@kaiyu , One more defect,
in the case when b.length() < a.length()
,
you are adding 0’s in b using this method
for (int i = 0; i < diff; ++i) {
b = '0' + b;
}
Time complexity of b = '0' + b;
itself is linear in size of string. (link)
So, complexity for whole for loop become O(n^2). That’s is pretty slow.
USE THIS
b.insert(b.begin(), diff, '0');
It’s complexity is linear in size of new string.
Checkout difference here.
Always be careful with string operations.