Amazon Interview Question
Software Engineer / DevelopersTeam: General
Country: United States
Interview Type: In-Person
<pre lang="" line="1" title="CodeMonkey48221" class="run-this">public class IntegerToString
{
public static void main(String[] args)
{
int integer = -987654321;
toString(integer, 10);
}
private static void toString(int integer, int radix)
{
StringBuilder string = new StringBuilder();
boolean isNegative = (integer < 0);
integer = Math.abs(integer);
double length = Math.log(integer) / Math.log(radix);
for (int i = 0; i < length; i++)
{
string.append(integer % radix);
integer /= radix;
}
if (isNegative)
string.append("-");
System.out.println(string.reverse());
}
}</pre><pre title="CodeMonkey48221" input="yes">
</pre>
... of course the for loop and the logarithms could be replaced by a do {} while (integer != 0) also
#include<iostream>
using namespace std;
void reverseString(char a[], int lowIndex, int highIndex)
{
if(lowIndex == highIndex)
return;
while(lowIndex < highIndex)
{
char tmp = a[lowIndex];
a[lowIndex] = a[highIndex];
a[highIndex] = tmp;
lowIndex++;
highIndex--;
}
}
char* intergerToString(int n)
{
static char a[1024];
int tmp;
int i = 0;
if(n < 0)
tmp = -n;
else
tmp = n;
if(tmp == 0)
{
a[0] = '0';
a[1] = '\0';
return a;
}
else
{
if(n < 0)
a[i++] = '-';
while(tmp > 0)
{
a[i++] = tmp % 10 + '0';
tmp /= 10;
}
i--;
if(a[0] == '-')
reverseString(a, 1, i);
else
reverseString(a, 0, i);
}
a[i + 1] = '\0';
return a;
}
void printString(char *a)
{
while(*a != '\0')
{
cout<<*a;
a++;
}
cout<<endl;
}
int main()
{
char *a = intergerToString(-12345);
printString(a);
}
why not use sprintf(s,"%d",num);
- Saurya November 09, 2011