String to Integer (atoi) – Leetcode #8

PROBLEM STATEMENT

This question is from Leetcode – String to Integer (atoi). The problem statement in short is given below:

Implement a function that converts a string to a 32-bit signed integer.

SOLUTION

public int myAtoi(String s) {

		int strToInt = 0;

		s = s.strip();
		int len = s.length();	
		StringBuilder str = new StringBuilder();
		boolean isNeg = false;

		for(int i=0; i<len; i++) {

			Character c = s.charAt(i);

			if(i == 0 &&  (c == '-'  ||  c == '+') ) {

				// if '-' is the first char then turn the flag to true
				if(c == '-')
					isNeg = true;

				continue;
			}

			// if char is digit then append to string
			if(Character.isDigit(c)  ) {

				str = str.append( Character.toString(c) );
				continue;
			}

			// if char is not a digit then break
			if(!Character.isDigit(c) ) {

				break;
			}

		} // endfor


		// convert string to integer
		if(!str.isEmpty()) {
			try {
				strToInt = Integer.valueOf(str.toString());
			}
			// if val is too large for int then return the min / max int val
			catch(NumberFormatException nfe) {

				if(isNeg)
					return Integer.MIN_VALUE;
				else
					return Integer.MAX_VALUE;
			}

		}

		// if flag is true then multiply by -1
		if(isNeg) {
			strToInt = strToInt * -1;
		}

		return strToInt;
	}	

You can check out the code from Github here: String to Integer (atoi) – First Approach

PERFORMANCE ANALYSIS

RUNTIME4 ms | Beats 8.58 %
MEMORY42.84 MB | Beats 15.56 %
TIME COMPLEXITYO (N)

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top