Pregunta de entrevista de Meta

Write a code to convert an ASCII representation of a positive integer to it's numeric value.

Respuestas de entrevistas

Anónimo

15 dic 2010

why don't you just go $mask = 1; and then in your loop $sum += ($intMap[$s[$i]] * $mask); $mask *= 10; instead of doing the whole to the power and then rounding down...

2

Anónimo

15 dic 2010

@Vic Yeah, I realized that right after the interview. I was a little too nervous during the interview so didn't come up a better solution. I can also iterate the string from left to right instead of right to left. That way I can save one multiplication, for example: $sum = $sum*10 + $intMap[$s[$i]];

Anónimo

4 feb 2011

public static int asciiToNumerical(int ascii) { int value = 0; while (ascii != 0x0000) { value = (value * 10) + ((0xFF & ascii) - 48); ascii >>= 8; } return value; } // scans the input reversed, but it can be easily modified. // input: 0x32363138 -> output: 8162 // input: 0x393435 -> output: 549

Anónimo

10 jul 2011

If using C, you can just subtract "0" from the number char to get its value. E.g., "1"-"0" = 1 and so on. So the code could just do: int value = s[i]- "0" instead of defining intMap. Everyone should really learn C. #include main(){ char *s = "88934"; int sum=0; int i=0; while(i

Anónimo

16 dic 2010

// COnvertAsciiToItsNumericValue.cpp : Defines the entry point for the console application. // #include #include #include using namespace std; int getNumeric(unsigned Ascii) { int itr = sizeof(unsigned); int sum = 0; for(itr=sizeof(unsigned);itr>0;itr--) { sum = sum + ((((0xFF>((itr-1)*8)) - '0')*pow(10,(double)(itr-1)); } return sum; } void main() { unsigned Ascii = 0x30393435; int numeric = getNumeric(Ascii); }

1

Anónimo

14 dic 2010

function ascii_to_integer($s) { $intMap = array("0"=>0, "1"=>1, "2"=>2, ...); $mask =0; $sum = 0; for ($i = strlen($s) - 1; $i >=0; $i--) { $sum = $sum + $intMap[$s[$i]] * round(power(10, mask),0); $mask++; } return $sum; }