It's an interview question, I was asked to compare 2 strings, and the number in the string are evaluated to integers when comparing.
I can use C/C++ and can not use stl or stdlib. Some test cases are showed in the code.
I submitted the code below but failed. The interviewer said that the code is not clean enough. Can anybody review the code?
#include <cstdio>
#include <cmath>
bool is_num(char x) {return (x>='0' && x<='9');}
int get_num(const char* s, int len)
{
int j = 0;
int ret = 0;
while (len > 0)
{
ret += (s[j++] - '0') * pow(10, len-1);
len --;
}
return ret;
}
int my_compare(const char* s1, const char* s2)
{
while((*s1)&&(*s2))
{
int value1 = 0;
int value2 = 0;
bool is_t1_num = false;
bool is_t2_num = false;
int len_t1 = 0;
int len_t2 = 0;
const char* t1;
const char* t2;
if (is_num(*s1))
{
t1 = s1;
while(is_num(*t1)&&(*t1))
{
len_t1 ++;
t1++;
}
value1 = get_num(s1, len_t1);
is_t1_num = true;
}
if (is_num(*s2))
{
t2 = s2;
while(is_num(*t2)&&(*t2))
{
len_t2 ++;
t2++;
}
value2 = get_num(s2, len_t2);
is_t2_num = true;
}
if ((!is_t1_num) && (!is_t2_num))
{
if ((*s1) < (*s2)) return -1;
if ((*s1) > (*s2)) return 1;
s1++;
s2++;
}
if ((is_t1_num) && (is_t2_num))
{
if (value1 < value2) return -1;
if (value1 > value2) return 1;
s1 += len_t1;
s2 += len_t2;
}
if ((is_t1_num) && (!is_t2_num))
{
if (value1>0) return 1;
s1 += len_t1;
}
if ((!is_t1_num) && (is_t2_num))
{
if (value2>0) return -1;
s2 += len_t2;
}
}//end while
if (!(*s1) && !(*s2)) return 0;
if (!(*s1)) return -1;
if (!(*s2)) return 1;
}
int main()
{
//TEST CASE 0
printf("%d\n", my_compare("ab", "1"));
printf("%d\n", my_compare("123", "456"));
printf("%d\n", my_compare("abc", "def"));
printf("%d\n", my_compare("abc123def", "abc000def"));
printf("%d\n", my_compare("ab", "abc"));
//TEST CASE 1
printf("%d\n", my_compare("abc000def", "abcdef"));
printf("%d\n", my_compare("abc101def", "abcdef"));
//TEST CASE 2
printf("%d\n", my_compare("abc101def", "abceef"));
}