Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
int isBig(char *s1, char *s2) {
int i, f = 0;
if (!(s1[i] || s2[i]))
return f;
for(i = 0; s1[i] && s2[i]; i++) {
printf("%c %c ",s1[i], s2[i]);
if (s1[i] == '.' && s2[i] == '.') {
if (f)
return f;
}
else if (s1[i] == '.')
return -1;
else if (s2[i] == '.')
return 1;
else if (s1[i] > s2[i] && f == 0)
f = 1;
else if (s2[i] > s1[i] && f == 0)
f = -1;
printf("%d\n",f);
}
if (f)
return f;
else if (s1[i])
return 1;
else if (s2[i])
return -1;
return 0;
}
Sorry with braces:
int isBig(char *s1, char *s2) {
int i, f = 0;
if (!(s1[i] || s2[i])) {
return f;
}
for(i = 0; s1[i] && s2[i]; i++) {
if (s1[i] == '.' && s2[i] == '.') {
if (f) {
return f;
}
}
else if (s1[i] == '.') {
return -1;
}
else if (s2[i] == '.') {
return 1;
}
else if (s1[i] > s2[i] && f == 0) {
f = 1;
}
else if (s2[i] > s1[i] && f == 0) {
f = -1;
}
}
if (f) {
return f;
} else if (s1[i]) {
return 1;
} else if (s2[i]) {
return -1;
}
return 0;
}
<pre lang="" line="1" title="CodeMonkey21736" class="run-this">class Main {
public static int compareVal(String a, String b) {
int compareVal = a.compareTo(b);
if(compareVal == 0) {
return 0;
} else if(compareVal < 0) {
return -1;
} else {
return 1;
}
}
public static int compareVersions(String versionA, String versionB) {
String[] aParts = versionA.split("\\.");
String[] bParts = versionB.split("\\.");
int numComparisons = Math.min(aParts.length, bParts.length);
for(int i = 0; i < numComparisons; ++i) {
int compareVal = compareVal(aParts[i], bParts[i]);
if(compareVal != 0) {
return compareVal;
}
}
if(aParts.length < bParts.length) {
for(int i = numComparisons; i < bParts.length; ++i) {
if(Integer.parseInt(bParts[i]) != 0) {
return -1;
}
}
} else if(aParts.length > bParts.length){
for(int i = numComparisons; i < aParts.length; ++i) {
if(Integer.parseInt(aParts[i]) != 0) {
return 1;
}
}
}
return 0;
}
public static void main(String[] args) {
System.out.println(compareVersions("1", "1"));
System.out.println(compareVersions("1", "0"));
System.out.println(compareVersions("1", "1.0"));
System.out.println(compareVersions("1.0", "1"));
System.out.println(compareVersions("1.1", "1.1.0.1"));
}
}
</pre><pre title="CodeMonkey21736" input="yes">
</pre>
Why wouldnt a simple string comparison work?
sum = str1[i] - str2[i];
if(sum == 0)
{
i++;
}
if(sum > 0) return 1;
if(sum < 0 ) return -1;
cases
str1[i] =1 str2[i] =1 -> sum =0;
str1[i] =1 str2[i] =2 -> sum = -1; meaning str2 is latest and vice versa
str1[i] =1 str2[i] = '.' ->sum = 3; str1 is line 'X1; and str2 is 'X.' meaning that
str1 is latest
If I could write this in COBOL, I would use the first variable and split this into an array of variables delimited by '.'. Then I would use a FOR loop to compare both the arrays and if I find that one is greater than the other I would break thge loop and come out and display that the answer
- Sri October 17, 2011