Write a program converts from string to integer.
Algorithm Explanation
![]() | Pass string format number to utility function. If the string is null, return 0. |
![]() | If it starts with -, assign a flag to -. Iterate the string and convert each char to string. If the flag is -, change the result to the negative number. |
![]() | Return and print the value. |
Source Code
package com.dsacode.DataStructre.array; public class ASCIItoInteger { public int atoi(String str) { if (str == null || str.length() < 1) return 0; str = str.trim(); char flag = '+'; int i = 0; if (str.charAt(0) == '-') { flag = '-'; i++; } else if (str.charAt(0) == '+') { i++; } double result = 0; while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') { result = result * 10 + (str.charAt(i) - '0'); i++; } if (flag == '-') result = -result; if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int) result; } public static void main(String[] args) { ASCIItoInteger a = new ASCIItoInteger(); int res = a.atoi("345"); System.out.println("convert '345' to integer: " + res); } }
Output
Convert '345' to integer: 345