Write a program to implement atoi function.
1) discard all the leading spaces
2) the string may optionally contain leading sign character
-12
+998
are valid
3) After these, if the next character is not a digit, then the return value must be 0
4) If there are alphabets or other characters after digits, the conversion should stop.
e.g.
-12ab89 = -12
ab129 = 0
890jkl = 890
How do we write code for this?
- For spaces, we must use trim function.
- For sign we should check if the 0th character is sign and if it is -, set the negative flag.
- While the character is digit,
- scan the character d
- Multiply previous sum s by 10
- Add the d -> s = s*10 +d
Not too complicated right. If we assign s to 0 initially, if there are no leading digits, we stop conversion and return 0. If there are digits followed by alpha, we stop at first alpha then return the value.
import java.util.Scanner; public class Atoi { int stringToInteger(String str){ str = str.trim(); char arr[] = str.toCharArray(); int len = arr.length; int sum = 0; boolean isNegative = false; int i=0; if(arr[0]=='-' ){ isNegative = true;i++; }else if(arr[0]=='+'){ i++; } for(;i<len;i++){ if(!Character.isDigit(arr[i])){ break;/* we have a non-digit. stop conversion*/ } sum = sum*10+(arr[i]-48);/*unicode value of 0 is 48*/ } if(isNegative) return -1*sum; return sum; } public static void main(String args[]){ String str; System.out.println("Enter a string"); Scanner scanner = new Scanner(System.in); str = scanner.nextLine(); Atoi obj = new Atoi(); System.out.println("THe number is "+obj.stringToInteger(str)); } }
Comments
Post a Comment