www.fatihkabakci.com

Personal Website and Computer Science TUR EN

Interview Question String to Integer (atoi)

Last update: 11/22/2016 10:04:00 AM

By Fatih KABAKCI

The problem is to convert a String to a Integer by considering all possible input elements to give correct output to the user. The steps have been explained in the Java program.

Problem #8 - String to Integer (atoi).

Description: Implement atoi to convert a string to an integer.

Difficulty: Easy

Solution in Java

package com.fatihkabakci.Easy.Atoi;

/**
 * 
 * @author fkabakci
 * Problem Description: Implement atoi to convert a string to an integer.
 * 
 * Examples:
 * 
 * Example1: String x = "+123", return 123 as Integer
 * 
 * Example2: String x = "-123", return -123 as Integer
 * 
 * Example3: String x = "45.23,45", return 45 as Integer
 * 
 * Example4: String x = "2147483649", return 2147483647 as Integer
 * 
 * Solution:
 * 1. Ignore whitespace characters
 * 
 * 2. Check it if it has no character
 * 		if there is no, return 0
 * 
 * 3. Check it if it starts with "+" or "-" operator
 * 		if so, remove the first character
 * 
 * 4. Check it how many comma or dot it has,
 * 		if more than 1, input invalid then return 0,
 * 		otherwise cut by starting from either dot or comma operator to the rest of the string.
 * 
 * 5. Check it if it has a special character
 * 		if so, cut by starting from the special character to the rest of the string.
 * 
 * 6. Check the boundaries and see that how many digits there are,
 * 		if more than 10, then return either INT_MAX or INT_MIN depending on whether the sign is positive or negative
 * 
 * 7. Get each character then figure out its ASCII values. Then convert it to the integer by subtracting ASCII 0.
 * 		if overflow comes up, then fix the value by decreasing the total by distance from INT MAX.
 * 
 * 8. return total.
 */
public class StringToInteger {

	private int asciiToDigit(char c) {
		return c - "0";
	}
	private int frequency(String str, char c) {
		int counter = 0;
		for(int i = 0; i < str.length(); i++) {
			if(str.charAt(i) == c)
				counter++;
		}
		return counter;
	}
	
	private int hasSpecialCharacter(String str) {
		for(int i = 0; i < str.length(); i++) {
			if(!Character.isDigit(str.charAt(i)))
				return i;
		}
		return -1;
	}
	
	public int myAtoi(String str) {
		str = str.trim();
		
		if(str.isEmpty())
			return 0;
		
		// for + or -
		short sign = 1;
		char first = str.charAt(0);
		if (first == "+") {
			sign = 1;
			str = str.substring(1);
		}
		else if (first == "-") {
			sign = -1;
			str = str.substring(1);
		}
		
		// for commas
		int commaCounter = frequency(str, ",");
		if(commaCounter > 1)
			return 0;
		
		int commaIndex = str.indexOf(",");
		if (commaIndex != -1)
			str = str.substring(0, commaIndex);
		
		// for dots
		int dotCounter = frequency(str, ".");
		if(dotCounter > 1)
			return 0;
		
		int dotIndex = str.indexOf(".");
		if (dotIndex != -1)
			str = str.substring(0, dotIndex);
		
		// for specials
		int specialCharacterIndex = hasSpecialCharacter(str);
		if(specialCharacterIndex != -1)
			str = str.substring(0, specialCharacterIndex);
		
		// conversion
		
		int order = str.length();
		// boundaries
		if (order > 10)
			if (sign > 0)
				return Integer.MAX_VALUE;
			else
				return Integer.MIN_VALUE;
		
		int sum = 0;
		for (int i = 0; i < order; i++) {
			char ascii = str.charAt(i);
			int digit = asciiToDigit(ascii);
			for (int k = 1; k < order - i; k++) {
				digit = digit * 10;
			}
			sum = sum + digit;
			// overflow
			if (sum < 0) {
				if (sign == -1)
					sum = sum - (sum - 1 - Integer.MAX_VALUE);
				else
					sum = sum - (sum - Integer.MAX_VALUE);
			}
		}
		return sign * sum;
	}

	public static void main(String[] args) {
		StringToInteger converter = new StringToInteger();
		System.out.println(converter.myAtoi(""));
		System.out.println(converter.myAtoi(" "));
		System.out.println(converter.myAtoi("123"));
		System.out.println(converter.myAtoi("+123"));
		System.out.println(converter.myAtoi("-123"));
		System.out.println(converter.myAtoi("45.23"));
		System.out.println(converter.myAtoi("45.23,45"));
		System.out.println(converter.myAtoi("24,01"));
		System.out.println(converter.myAtoi("" + Integer.MAX_VALUE));
		System.out.println(converter.myAtoi("abc"));
		System.out.println(converter.myAtoi("3*2"));
		System.out.println(converter.myAtoi("010"));
		System.out.println(converter.myAtoi("  -0012a42"));
		System.out.println(converter.myAtoi("-2147483647")); // -2147483647
		System.out.println(converter.myAtoi("2147483647")); // 2147483647
		System.out.println(converter.myAtoi("2147483649")); // 2147483647
		System.out.println(converter.myAtoi("-2147483648")); // -2147483648
		System.out.println(converter.myAtoi("-2147483649")); // -2147483648
		System.out.println(converter.myAtoi("10522545459")); // 2147483647
		System.out.println(converter.myAtoi("-10522545459")); // -2147483648
	}
}

Output order:

1. 0
2. 0
3. 123
4. 123
5. -123
6. 45
7. 45
8. 24
9. 2147483647
10. 0
11. 3
12. 10
13. -12
14. -2147483647
15. 2147483647
16. 2147483647
17. -2147483648
18. -2147483648
19. 2147483647
20. -2147483648

There has been no comment yet

Name:


Question/Comment
   Please verify the image




The Topics in Computer Science

Search this site for





 

Software & Algorithms

icon

In mathematics and computer science, an algorithm is a step-by-step procedure for calculations. Algorithms are used for calculation, data processing, and automated reasoning.

Programming Languages

icon

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. It can be used to create programs to control the behavior of a machine. Java,C, C++,C#

Database

icon

A database is an organized collection of data. The data are typically organized to model aspects of reality in a way that supports processes requiring information.

Hardware

icon

Computer hardware is the collection of physical elements that constitutes a computer system. Computer hardware refers to the physical parts or components of a computer such as the monitor, memory, cpu.

Web Technologies

icon

Web development is a broad term for the work involved in developing a web site for the Internet or an intranet. Html,Css,JavaScript,ASP.Net,PHP are one of the most popular technologies. J2EE,Spring Boot, Servlet, JSP,JSF, ASP

Mobile Technologies

icon

Mobile application development is the process by which application software is developed for low-power handheld devices, such as personal digital assistants, enterprise digital assistants or mobile phones. J2ME

Network

icon

A computer network or data network is a telecommunications network that allows computers to exchange data. In computer networks, networked computing devices pass data to each other along data connections.

Operating Systems

icon

An operating system is software that manages computer hardware and software resources and provides common services for computer programs. The OS is an essential component of the system software in a computer system. Linux,Windows

Computer Science

icon

Computer science is the scientific and practical approach to computation and its applications.A computer scientist specializes in the theory of computation and the design of computational systems.