Skip to main content

Convert String to Integer

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?

  1. For spaces, we must use trim function.
  2. For sign we should check if the 0th character is sign and if it is -, set the negative flag.
  3. While the character is digit, 
    1. scan the character d
    2. Multiply previous sum s by 10
    3. 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

Popular posts from this blog

Binary numbers in Java

Write a program to add two binary numbers in Java. Before you start thinking about long binary arithmetic operation, be happy for the fact that Java has inbuilt mechanism for writing binary literals and displaying a number in binary. If we prefix a number with 0b, the number will be treated as binary literal.    e.g. int num1 = 0b1110;/* binary value*/ int num2 = 0b0001; To convert a number to binary - or to display a number in binary, we can use the method toBinaryString() in Integer class.  int a = 10; String st = Integer.toBinaryString(a);/*st is 1010*/ Now we just write a simple program to add two binary literals and display the answer in binary. public class Demo { public static void main ( String args []) { int m = 0 b110011 ; int n = 0 b101100 ; int ans = m + n ; System . out . println ( "The sum of two numbers is " + Integer . toBinaryString ( ans )); } } By the way, do y...

Reverse string using recursion

While we are at it, let us write another recursive function - a function to reverse the characters of a string. Write a recursive function to reverse a string  To reverse a string, we can use this algorithm If the string is not empty return substring of last n-1 characters +first character To reverse the string we need to move the characters from begining of string to end of string. We take the string, some how we reverse last n-1 characters and then add the first character to the end. Let us look at an example of reversing the 5 letter string Hello  Reverse Hello Reverse ello + H reverse llo+e reverse lo+l reverse o+l reverse ""+o The last call just returns the empty string. This returned value is available to previous call. This will return o. Then we go to the previous call of function which will add l to this and return lo. Then we move up the function stack and add l to this lo and return llo. And so on. Here is the code   ...

Recursion - factorial

Write a recursive function to find factorial of a number. According to definition,    n! = n*(n-1)! Yes, the definition is recursive. Which makes our coding easier. Recursive function A function which invokes or calls itself is called a recursive function. Just like the definition given above, you write factorial(n-1) within factorial(int n) function. Now you may wonder, won't this type of function cause an infinite loop? It does, unless you create a base condition in which there is no recursive call. In this example, n = 0 is the base condition. So 0! is 1 and if n is 0 we just return 1. Here is how we have to write our recursive function for factorial. if n >0 return n* factorial(n-1) if n =0 return 1 Wow, so concise! And recursive functions are often deceptively small. Here is our complete function in Java int factorial ( int n ){ if ( n == 0 ) return 1 ; return n * factorial ( n - 1 ); }