Bloomberg LP Interview Question
Financial Software DevelopersCountry: United States
Interview Type: Phone Interview
Nice one for unsigned integer.
I'd only add error management, in case a not-an-integer were part of the string. In that case, you'd still return an integer.
And check for the sign in first place, as the atoi function does it.
How about below code??
int atoi(char *name)
{
int ascii=48; // ascii code for zero
int len = strlen(name)-1;
int index;
int intVal=0;
int tens=1;
for(index=len;index>=0; index--)
{
intVal = intVal+((name[index]-ascii)*tens);
tens= tens*10;
}
return intVal;
}
hey ur code is write but making number in reverse....
index value must be zero and not need to used strlen function...
for(index=0;name[index]!='\0';index++) okkk
Here is a solution.
I used switch-case to convert a single character into a digit.
A smarter way is to obtain the digit from the ASCII representation of the character.
static int atoi(string input)
{
int o = 0;
int sign = 1;
int digit = 0;
int startIndex = 0;
//Check for minus sign
if (input[0] == '-')
{
sign = -1;
startIndex = 1;
}
for (int i = startIndex; i < input.Length; i++)
{
switch (input[i])
{
case '0':
digit = 0;
break;
case '1':
digit = 1;
break;
case '2':
digit = 2;
break;
case '3':
digit = 3;
break;
case '4':
digit = 4;
break;
case '5':
digit = 5;
break;
case '6':
digit = 6;
break;
case '7':
digit = 7;
break;
case '8':
digit = 8;
break;
case '9':
digit = 9;
break;
default: //Not a char
throw new ArgumentException("non-numeric digit was found.", "input");
}
o += (int)(Math.Pow(10, input.Length - i - 1) * digit);
}
return o * sign;
}
Working Java implementation :
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "786786";
int length = input.length();
int sum = 0;
int convertedDig = 0; //Converted digit from char
int startIndex = 0; //StartIndex based on sign
int sign = 1; //Default sign is +ve.
//Check for -ve number.
if(input.charAt(0) == '-'){
sign = -1;
startIndex = 1;
}
//Iterate over String starting from 1st digit.(startIndex)
//
for(int i=startIndex;i<length;i++){
switch(input.charAt(i)){
case '0' : convertedDig = 0; break;
case '1' : convertedDig = 1; break;
case '2' : convertedDig = 2; break;
case '3' : convertedDig = 3; break;
case '4' : convertedDig = 4; break;
case '5' : convertedDig = 5; break;
case '6' : convertedDig = 6; break;
case '7' : convertedDig = 7; break;
case '8' : convertedDig = 8; break;
case '9' : convertedDig = 9; break;
}
sum += convertedDig * Math.pow(10, (length-i-1));
}
System.out.println("The atoi conversion is "+sum*sign);
}
int atoi (string strval)
{
int intval = 0, negval = 0;
for (int i=0; i < strval.size() && isspace(strval[i]); i++) ;
if (i < strval.size() && strval[i] == '-' ) negval = 1;
for ( ; i < strval.size() && isdigit(strval[i]) ; i++) {
intval = (intval * 10) + (strval[i] - '0');
}
return (negval == 1 ? -intval : intval)
}
#include <iostream>
#include <string>
using namespace std;
int convert_string()
{
cout<<"Please input your string-number here: "<<endl;
string in;
cin >> in ;
double tens(1),sum(0);
for(int i= in.length()-1 ; i>=0 ; i--)
{
sum += (int(in[i])-int('0'))*tens;
tens *= 10;
}
cout<<sum<<endl;
return sum;
}
int convert_char()
{
cout<<"Please input your string-number here: "<<endl;
char in[100];
cin >> in ;
double tens(1),sum(0);
int j = 0;
int count = 0;
while(in[j]!='\0')
{
j++;
count++;
}
for(int i= count-1 ; i>=0 ; i--)
{
sum += (int(in[i])-int('0'))*tens;
tens *= 10;
}
cout<<sum<<endl;
return sum;
}
int my_atoi2(char* in) {
int n = 0;
if (in) {
char* e = in;
int neg = 1;
if (*e == '-') {
neg = -1;
e++;
} else if (*e == '+')
e++;
while (*e != 0) {
if (*e < '0' || *e > '9') {
n = 0;
break;
}
n *= 10;
n += (int)(*e - '0');
e++;
}
n *= neg;
}
return n;
}
I will give you an error-free solution. If anyone finds some bugs, please let me know.
public class ATOI {
public static int atoi(String str) {
int sign = 1;
int startIndex = 0;
int digit = -1;
StringBuilder num = new StringBuilder();
if (str.charAt(0) == '-' || str.charAt(0) == '+') {
if(str.charAt(0) == '-'){
sign = -1;
}
startIndex = 1;
}
while(str.charAt(startIndex) == '0'){
startIndex++;
}
for (int i = startIndex; i < str.length(); i++) {
switch (str.charAt(i)) {
case '0':
digit = 0;
break;
case '1':
digit = 1;
break;
case '2':
digit = 2;
break;
case '3':
digit = 3;
break;
case '4':
digit = 4;
break;
case '5':
digit = 5;
break;
case '6':
digit = 6;
break;
case '7':
digit = 7;
break;
case '8':
digit = 8;
break;
case '9':
digit = 9;
break;
default:
digit = -1;
break;
}
if (digit == -1) {
break;
} else {
num.append(digit);
}
}
return sign * Integer.parseInt(num.toString());
}
public static void main(String[] args) {
System.out.println(atoi("+00345 78"));
System.out.println(atoi("-00345 78"));
System.out.println(atoi("345ij 78"));
System.out.println(atoi("80 +45"));
}
}
Here's a template C++ function that works for any integer types and reports all error conditions.
#include <limits>
#include <string>
#include <cctype>
#include <cassert>
#include <type_traits>
template<typename TChar, typename TNumber> bool my_atoi(const std::basic_string<TChar>& str, TNumber& result)
{
typedef std::make_unsigned<TNumber>::type TNumberUnsigned;
// check if result type is integer
assert(std::numeric_limits<TNumber>::is_integer);
auto currChar = str.cbegin();
// use corresponding unsigned type to accumulate number to avoid overflows for numbers such as -128
TNumberUnsigned number = 0;
bool isNegative = *currChar == '-';
if (isNegative) {
// negative numebers can only be parsed into signed types
if (!std::numeric_limits<TNumber>::is_signed)
return false;
++currChar;
}
// empty string or string containing just - sign are not valid integers
if (currChar == str.cend())
return false;
while (currChar != str.cend()) {
auto digit = *currChar - '0';
// check that the next digit is valid
if (digit < 0 || digit > 9)
return false;
// check for overflow
if (number > std::numeric_limits<TNumberUnsigned>::max() / 10)
return false;
number *= 10;
// check for overflow
if (number > std::numeric_limits<TNumberUnsigned>::max() - digit)
return false;
number += digit;
++currChar;
}
if (isNegative) {
// correctly check for negative overflow (-128)
if (number > static_cast<TNumberUnsigned>(std::numeric_limits<TNumber>::max()) + 1)
return false;
result = static_cast<TNumber>(-1 * number);
}
else {
if (number > static_cast<TNumberUnsigned>(std::numeric_limits<TNumber>::max()))
return false;
result = static_cast<TNumber>(number);
}
return true;
}
Here is a solution.
I used switch-case to convert a single character into a digit.
A smarter way is to obtain the digit from the ASCII representation of the character.
static int atoi(string input)
{
int o = 0;
int sign = 1;
int digit = 0;
int startIndex = 0;
//Check for minus sign
if (input[0] == '-')
{
sign = -1;
startIndex = 1;
}
for (int i = startIndex; i < input.Length; i++)
{
switch (input[i])
{
case '0':
digit = 0;
break;
case '1':
digit = 1;
break;
case '2':
digit = 2;
break;
case '3':
digit = 3;
break;
case '4':
digit = 4;
break;
case '5':
digit = 5;
break;
case '6':
digit = 6;
break;
case '7':
digit = 7;
break;
case '8':
digit = 8;
break;
case '9':
digit = 9;
break;
default: //Not a char
throw new ArgumentException("non-numeric digit was found.", "input");
}
o += (int)(Math.Pow(10, input.Length - i - 1) * digit);
}
return o * sign;
}
how about this ? suggestions please...
- amber June 12, 2012