## Linkedin Interview Question

Software Engineer / Developers**Country:**United States

**Interview Type:**In-Person

int convert(char* str, int base){

int value = 0;

int basePower = 1;

// assuming value supplied in str belongs to base

int length = strlen(str);

for(int i = length-1; i >= 0; i++){

if(i == 0 && str[i] == '-'){

value *= -1;

continue;

}

value += (str[i] - '0')*basePower; // this would have worked if digits were // followed by alphabets in ASCII table

basePower *= base;

}

return value;

}

Convert first into binary. From binary, do octal. From binary, do hex. O(n) time each. For octal/hex conversion, create a map such that a["001"] = 1, a["111"]=7 for octal, and for hex b["1111"]="f". O(1) memory, O(n) to convert decimal to binary. Then, O(n) to map the bits to octal or hex using map.

string is "a1b" (base 16): return value should be 2587.

- Anonymous November 05, 2011