Amazon Interview Question
Software Engineer InternsCountry: United States
Interview Type: Phone Interview
Missing a lot boundary cases. It won't work for alphanumeric strings, +123, -123. In case of null or empty strings, it will return 0 which is wrong.
int main(int argc, _TCHAR* argv[])
{
char * str = "586";
int sum = 0;
for (int i = 0; str[i] !='\0'; i++)
{
sum = sum * 10 + (str[i] - '0');
}
cout << sum << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
int toInt(char *value){
int ind = 0, sum = 0, multiplier = 0;
// find the length of value
// or number of characters present in value
if ( value[0] == '-' ){
for(ind=1; value[ind] != '\0'; ind++);
ind--;
while( ind >= 1 ) {
if(multiplier == 0) {
sum = (value[ind] - '0' ) ;
multiplier = 10;
}
else{
sum = sum + (multiplier * (value[ind] - '0' ));
multiplier = multiplier * 10;
}
ind--;
}
return sum*-1;
}
else {
for(ind=0; value[ind] != '\0'; ind++);
ind--;
while( ind >= 0 ) {
if(multiplier == 0) {
sum = (value[ind] - '0' ) ;
multiplier = 10;
}
else{
sum = sum + (multiplier * (value[ind] - '0' ));
multiplier = multiplier * 10;
}
ind--;
}
return sum;
}
}
void main() {
char *value = "6834";
printf("\n\n %d ", toInt(value)); // gives 6834
// works for negative numbers as well.. :)
}
you just need to implement the atoi() function from c library.
here is the hint:
1) You set the pointer at the start of the char array.
2) And then inside for loop you go over each character and multiply by 10 and add the character by subtracting by 0, and store it in the result.
something like:
/*
int res=0;
for (int i = 0; str[i] != '\0'; ++i)
res = res*10 + str[i] - '0';
*/
And if you will try with "26745". the number would be 26745 as well.
and if you need to check for signed values like "-26745"
just check if charArray[0] is ' - '. if so, store it in a variable(eg: int sign= -1 ;)
then iterate the loop from i=1 and return sign*res;
which will return -26745 for "-26745".
#include<iostream>
#include<climits>
#include<cstdlib>
#include<cctype>
using namespace std;
int convertStringToInt(char * str,int &a)
{
if(NULL == str)
{
return -1;
}
bool isNeg = false;
char * start = str;
while(isspace(*start))
{
++start;
}
if(*start == '-')
{
isNeg = true;
++start;
}
while(*start)
{
if(*start >= '0' && *start <= '9')
{
if(!isNeg && a > (INT_MAX - (int)*start + '0')/10)
{
cout<<"overflow"<<endl;
return -1;
}
if(isNeg && a > ((abs(INT_MIN)) - (int)*start + '0')/10)
{
cout<<"underflow"<<endl;
return -1;
}
a = a*10 + (int)*start - '0';
}
++start;
}
if(isNeg)
{
a = -1*a;
}
return 0;
}
int main()
{
int a =0;
char str[] = " 214748hh";
int result = convertStringToInt(str,a);
if(result == 0)
{
cout<<"Value: "<<a<<endl;
}
return 0;
}
// practicebrainbench.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <regex>
using namespace std;
int find(char* str)
{
char* s = str;
int count[123];
int counter=0;
for(int i=0;i<123;i++) count[i] = 0;
while( *s != '\0')
{
if(count[*s] == 0)
{
count[*s]++;
s++;
counter++;
}
else
{
return counter;
}
}
return 0;
}
int count( int S[], int m, int n )
{
// If n is 0 then there is 1 solution (do not include any coin)
if (n == 0)
return 1;
// If n is less than 0 then no solution exists
if (n < 0)
return 0;
// If there are no coins and n is greater than 0, then no solution exist
if (m <=0 && n >= 1)
return 0;
// count is sum of solutions (i) including S[m-1] (ii) excluding S[m-1]
return count( S, m - 1, n ) + count( S, m, n-S[m-1] );
}
template<class T>
T getmax(T a,T b)
{
T result;
result = (a>b)?a:b;
return result;
}
class A
{
int i;
char* s;
public:
A( int j):i(j)
{
s = new char(10);
strcpy(s,"Keyur");
}
A()
{
s = new char(10);
strcpy(s,"Keyur");
}
virtual void fun() { cout<<"A func"<<endl; }
void print()
{
cout<<&i<<endl;;
cout<<&s<<endl;;
}
A operator + (const A& rhs)
{
A obj;
obj.i = i + rhs.i;
return obj;
}
A(const A& obj)
{
i = obj.i;
s = new char(strlen(obj.s) + 1);
strcpy(s,obj.s);
}
A& operator = (const A& obj)
{
if( &obj != this)
{
i = obj.i;
delete []s;
s = new char(strlen(obj.s) + 1);
strcpy(s,obj.s);
return *this;
}
}
};
int getnum(int a[],int n)
{
int max=0;
for(int i=0;i<n;i++)
{
if (a[i] > max )
max = a[i];
}
return max;
}
int num(char* s)
{
char* temp = s;
int len = strlen(s);
int a=0,sum=0;
int i=0;
while(*temp)
{
a = *temp - 48;
a = a * pow(10,len-1-i);
sum = sum + a;
i++;
temp++;
}
return sum;
}
int main()
{
char* s ="10000001";;
cout<<num(s);
getchar();
return 0;
}
In C#, just to change things up. Works with negative
public static int ToInt(string str)
{
int result = 0;
char[] cArr = str.ToCharArray();
// account for negative
int end = cArr[0] == '-' ? 1 : 0;
for (int i = str.Length - 1, j = 1; i >= end; i--, j *= 10)
{
int digit = ToInt(cArr[i]);
result += digit * j;
}
if (end == 1)
result *= -1;
return result;
}
public static int ToInt(char c)
{
return (int)c - 48;
}
str = str.trim();
int i = 0;
int n = str.length();
int sign = 1;
while(i<n && str.charAt(i)=='+'){
i++;
}
while(i<n && str.charAt(i)=='-'){
sign==-1;
i++;
}
int ans = 0;
while(i<n && Character.isDigit(str.charAt(i))){
int digit = Character.getNumericValue(str.charAt(i));
if(ans>Integer.MAX_VALUE/10 || (ans>Integer.MAX_VALUE/10 && digit>7)){
return sign==1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
ans = ans*10 + digit;
i++;
}
return sign* ans;
// Program needs to be modified for all digits 0-9
public static void main(String[] args)
{
String str = "586";
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
hm.put('5',5);
hm.put('8',8);
hm.put('6',6);
int sum = 0 ;
int sign = 1;
for(int i = 0 ; i<str.length() ; i++){
if(str.charAt(i) == '-'){
sign = -1;
continue;
}
int x = hm.get(str.charAt(i));
sum += (x * Math.pow(10,(str.length() - i - 1)));
}
System.out.println(sum*sign);
}
Hi
- Bracelet July 01, 2014This function should work well. Short and sweet
int num(char* s)
{
char* temp = s;
int len = strlen(s);
int a=0,sum=0;
int i=0;
while(*temp)
{
a = *temp - 48;
a = a * pow(10,len-1-i);
sum = sum + a;
i++;
temp++;
}
return sum;
}