Write a function to convert an input string to an integer.OR write your own atoi function.

The atoi  function defined in stdlib.h in C converts a String to an int. The declaration of atoi( ) is as following :

int atoi(const char *str);

Here we are going to write our own atoi() implementation in Java. Remember in Java you convert a string to an integer using the parseInt method of the Java Integer class. The parseInt method converts the String to an int, and throws a NumberFormatException if the string can’t be converted to an int type.

But here we will try to write the functionality using an algorithm which is different than just parsing the String to int.

  1. The function first discards all whitespace characters until the first non-whitespace character is found.
  2. 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.
  3. The string can contain additional characters other than numerical values, which are ignored and have no effect on the behaviour of this function.
  4. If the first sequence of non-whitespace characters in str is not a valid integral number, or if the String is empty or it contains only whitespace characters, no conversion is performed.
  5. If no valid conversion could be performed, a zero value is returned.
  6. If the algorithm can convert the input String to a numerical value but which is out of range then INT_MAX (2147483647) or  INT_MIN (-2147483648) is returned.
package com.tuturself.rec;

public class StringToInteger {

    public static int myAtoi(String inNumberStr) {
        if (inNumberStr == null || inNumberStr.trim().length() == 0) {
            return 0;
        }

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

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

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

        int length = inNumberStr.length();
        int start = -1;
        int index = 0;
        for (; index < length; index++) {
            char a = inNumberStr.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 = inNumberStr.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;
    }

    public static void main(String args[]) {
        System.out.println("1. valid conversion shuold return 1234 : " + myAtoi("1234"));
        System.out.println("2. valid conversion positive number should return 901234 :" + 
                     myAtoi("+901234"));
        System.out.println("3. valid conversion negative number should return -981234 :" + 
                     myAtoi("-981234"));
        System.out.println("4. Invalid input null should return 0 :" + myAtoi(null));
        System.out.println("5. Invalid input out of range negative value should return -2147483648:" 
                     + myAtoi("-21474836499"));
        System.out.println("6. Invalid input out of range positive value should return -2147483647 :"
                     + myAtoi("2147483648"));
    }
}

Output of the program:

1. valid conversion shuold return 1234 : 1234
2. valid conversion positive number should return +901234 :901234
3. valid conversion negative number should return -981234 :-981234
4. Invalid input null should return 0 :0
5. Invalid input out of range negative value should return -2147483648:-2147483648
6. Invalid input out of range positive value should return -2147483647 :2147483647

 

core java 12 Algorithm 12

FOLLOW US ON LinkedIn



Explore Tutu'rself