Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Written Test
Null terminated string? Should the function's return type be char* ? If so, the caller will need to worry about the memory problem then, which I don't think is a very good way. If the function returns a string as an object, then the null terminated request will be redundant. Here is my C++ solution:
string intToString(int n)
{
if(n == 0) return "0";
string s;
if(n < 0){
s.push_back('-');
n = -n;
}
for(; n; n /= 10) s.push_back(n%10 + '0');
char c;
for(int i = s[0] == '-', j = s.size()-1; i < j; ++i, --j){
c = s[i];
s[i] = s[j];
s[j] = c;
}
return s;
}
public class numToStr {
public static void numToStrVal(int a,String s){
if(a>0){
s=a%10+s;
numToStrVal(a/10,s);
}
else
System.out.println(s);;
}
public static void main(String[] args) {
numToStrVal(324,"\0");
}
}
string itoa(int num){
if (num == 0) return "0";
string ret_string;
if (num < 0){
ret_string.push_back('-');
num = -num;
}
while (num !=0){
ret_string.push_back(num%10 + '0');
num = num/10;
}
ret_string.push_back('\0');
//swap
for(int i = ret_string[0] == '-', j = ret_string.size()-2; i <j ; i++, j--){
ret_string[i] = ret_string[i] ^ ret_string[j];
ret_string[j] = ret_string[i] ^ ret_string[j];
ret_string[i] = ret_string[i] ^ ret_string[j];
}
return ret_string;
}
C++ version:
#include <iostream>
#include <string>
using namespace std;
string itoa(int i)
{
return to_string(i);
}
int main() {
std::cout << itoa(0) << std::endl;
std::cout << itoa(10) << std::endl;
std::cout << itoa(25) << std::endl;
std::cout << itoa(256) << std::endl;
std::cout << itoa(-10) << std::endl;
std::cout << itoa(-25) << std::endl;
std::cout << itoa(-256) << std::endl;
}
Note that itoa is not part of the standard, so I have no qualms about obliterating it in my namespace.
Or try this:
string itoa(int i)
{
string sign, magnitude;
if(i < 0)
{
i = -i;
sign = "-";
}
do
{
magnitude = static_cast<char>('0' + i%10) + magnitude;
i /= 10;
}while(i);
return sign + magnitude;
}
You must be kidding that you used std::to_string(). Do you think an interviewer will accept this? He wants you to implement that. That's the point of the question.
C++ version.
- Diego Giagio November 23, 2013