Today while solving a question on leetcode, I applied dfs on a directed graph which runs on O(N) time, but my code is giving TLE, so after trying too many time I checked on comments and there was a accepted code which also runs on O(N). So now I am confused as why my code is not getting accepted and giving time limit exceeded. My code:-
<code>class Solution {
public:
string multiply(string num1, string num2) {
int i=0,j=0;
int n=0 , m=0;
while(i<num1.size()){
if((n>INT_MAX/10) ||(n==INT_MAX/10 && num1[i]>'7') ){
n=INT_MAX;
}
n = n * 10 + (num1[i]-'0');
++i;
}
while(j<num2.size()){
if((m>INT_MAX/10) ||(m==INT_MAX/10 && num2[i]>'7') ){
m=INT_MAX;
}
m = m * 10 + (num2[j]-'0');
++j;
}
long long int result;
result = m*n;
string ans;
ans = to_string(result);
return ans;
}
};
</code>
<code>class Solution {
public:
string multiply(string num1, string num2) {
int i=0,j=0;
int n=0 , m=0;
while(i<num1.size()){
if((n>INT_MAX/10) ||(n==INT_MAX/10 && num1[i]>'7') ){
n=INT_MAX;
}
n = n * 10 + (num1[i]-'0');
++i;
}
while(j<num2.size()){
if((m>INT_MAX/10) ||(m==INT_MAX/10 && num2[i]>'7') ){
m=INT_MAX;
}
m = m * 10 + (num2[j]-'0');
++j;
}
long long int result;
result = m*n;
string ans;
ans = to_string(result);
return ans;
}
};
</code>
class Solution {
public:
string multiply(string num1, string num2) {
int i=0,j=0;
int n=0 , m=0;
while(i<num1.size()){
if((n>INT_MAX/10) ||(n==INT_MAX/10 && num1[i]>'7') ){
n=INT_MAX;
}
n = n * 10 + (num1[i]-'0');
++i;
}
while(j<num2.size()){
if((m>INT_MAX/10) ||(m==INT_MAX/10 && num2[i]>'7') ){
m=INT_MAX;
}
m = m * 10 + (num2[j]-'0');
++j;
}
long long int result;
result = m*n;
string ans;
ans = to_string(result);
return ans;
}
};
correct my code and give me the correct code
New contributor
Abhishek Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.