(String to Integer (atoi))

Implement atoi to convert a string to an integer.

Thoughts:
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Code (Java):

	public int atoi(String number) {
		if (number == null || number.trim().length() == 0) {
			return 0;
		}

		int result = 0;
		number = number.trim();

		boolean negate = false;
		char sign = number.charAt(0);

		if (sign == '+' || sign == '-') {
			if (sign == '-') {
				negate = true;
			}
			number = number.substring(1);
		}

		int length = number.length();
		int start = -1;
		int index = 0;
		for (; index < length; index++) {
			char a = number.charAt(index);
			if (a >= '0' && a <= '9') {
				if (start == -1)
					start = index;
			} else {
				break;
			}
		}
		int end = index - 1;

		if (start == -1)
			return 0;

		for (int i = start; i <= end; ++i) {
			char a = number.charAt(i);
			int digit = a - '0';
			if (!negate) {
				if (result + digit * (int) Math.pow(10, end - i) >= result)
					result += digit * (int) Math.pow(10, end - i);
				else
					result = Integer.MAX_VALUE;
			} else {
				if (result - digit * (int) Math.pow(10, end - i) <= result)
					result -= digit * (int) Math.pow(10, end - i);
				else
					result = Integer.MIN_VALUE;
			}
		}

		return result;
	}

Code (C++):

class Solution {
public:
    int atoi(const char *str) {
        if (str == NULL) {
            return 0;
        }
        string number(str);
        if(number.size() == 0)
            return 0;
        
        int i = 0;
        for(; i < number.size(); ++i) {
            if(!isspace(number[i])) {
                break;
            }
        }
        number = number.substr(i);
        int result = 0;
        
        bool negate = false;
        char sign = number[0];

        if (sign == '+' || sign == '-') {
            if (sign == '-') {
                negate = true;
            }
            number = number.substr(1);
        }

        int length = number.size();
        int start = -1;
        int index = 0;
        for (; index < length; index++) {
            char a = number[index];
            if (a >= '0' && a <= '9') {
                if(start == -1)
                    start = index;
            } else {
                break;
            }
        }
        int end = index - 1;

        if (start == -1)
            return 0;

        for (int i = start; i <= end; ++i) {
            char a = number[i];
            int digit = a - '0';
            if (!negate) {
                if (result + digit * (int) pow(10, end - i) >= result)
                    result += digit * (int) pow(10, end - i);
                else
                    result = INT_MAX;
            } else {
                if (result - digit * (int) pow(10, end - i) <= result)
                    result -= digit * (int) pow(10, end - i);
                else
                    result = INT_MIN;
            }
        }

        return result;
    }
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: