// val: integer that needs to be converted to string representation // destBuffer: buffer where the output string will be written // radix: is the radix of the numbering system (10 for decimal, 16 for Hexadecimal, // 2 for binary) char * my_itoa(int val, char * destBuffer, int radix) { if(val == 0) { destBuffer = "0"; return destBuffer; } bool isNeg = false; // if input integer is negative set the isNeg flag and make it positive // we will do the conversion using the absolute value and then append the // the - sign in the end if(val < 0) { isNeg = true; val *= -1; } char *currentDest = destBuffer; while(val > 0) { int digit = val % radix; val /= radix; *currentDest = (char) (digit + '0'); currentDest++; } if(isNeg) { *currentDest = '-'; currentDest++; } *currentDest = '\0'; reverse(destBuffer); return destBuffer; }
Frequently asked programming interview questions (with answers) and puzzles asked by google, microsoft, amazon, yahoo, and facebook for SDE/Developer and SDET positions.
String: Convert Integer to String itoa
Labels:
String Manipulation
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment