OnMobile Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Written Test
In C++ :
int lengthOfNumber (int num) {
int temp, i = 0;
temp = num;
while (temp > 0) {
temp = temp/10;
i++;
}
return i;
}
int returnIndex(int a, int b) {
int length_a = lengthOfNumber(a);
int length_b = lengthOfNumber(b);
int divisor = 10^length_a;
int counter = 0;
int rem = b, div = b;
while (div != 0) {
rem = rem%divisor;
if (rem == a)
return length_b - counter - length_a;
div = div/10;
counter++;
}
return -1; //a does not exist in b
}
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int numa = 126547;
int numb = 654;
int temp = numb;
int index = 0;
int traversal = 0;
if (numa < numb) {
temp = numa;
numa = numb;
numb = temp;
temp = numb;
}
while (numa > 0) {
if (temp > 0) {
if (numa % 10 == temp % 10) {
temp = temp / 10;
if (temp == 0)
index = traversal;
} else {
temp = numb;
}
}
numa = numa / 10;
traversal++;
}
if (temp > 0)
cout << " NOt found ";
else
cout << " Found at " << traversal - index;
}
In JAVA :
public class Test1 {
public static void main(String args[]) {
int a = 12345;
String sa = Integer.toString(a);
int saLen = sa.length();
int b = 34;
String sb = Integer.toString(b);
int sbLen = sb.length();
int match;
for( int i = 0 ; i < saLen ; i++ ) {
match = 1;
if( sa.charAt(i) == sb.charAt(0) ) {
for( int j = 0 ; j < sbLen ; j++ ) {
if( sa.charAt(i+j) != sb.charAt(j) ) {
match = 0;
break;
}
}
if( match == 1 ) {
System.out.println(" Index Found at i : " + i);
System.exit(0);
}
}
}
}
}
int intIndex(int a, int b)
{
// assume a and b are positive, otherwise use abs
int power = 1;
int a_len = 1, b_len = 1;
while (power < a)
{
a_len++;
power *= 10;
}
int index = -1;
for (int i = 0; b > 0; i++, b /= 10)
{
if (b % power == a)
{
index = i;
}
b_len++;
}
return (index > 0) ? (b_len - index - a_len) : -1;
}
Just correct the first answer.
BTW, the "^" symbol is not power in c++. It's bitwise XOR.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int length (int num) {
int temp, i = 0;
temp = num;
while (temp > 0) {
temp = temp/10;
i++;
}
return i;
}
int index(int a, int b) {
int len_a = length(a);
int len_b = length(b);
int divisor = static_cast<int>(pow(10,length_a));
int counter = 0;
int rem = b, div = b;
while (div != 0) {
int index = rem%divisor;
rem = rem/10;
if (index == a)
return len_b - counter - len_a;
div = div/10;
counter++;
}
return -1; //a does not exist in b
}
int main()
{
int a = 34, b = 12345;
int index = index(a, b);
printf("The index is: %d\n", index);
return 0;
}
result = greater number - smaller number
- Rajesh January 23, 2013In the result check if there are consecutive zeros of length equal to the length of smaller number(from right) , if so return the index where the last zero is present in the result