Open In App

Convert string to integer without using any in-built functions

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string str, the task is to convert the given string into the number without using any inbuilt function.

Examples: 

Input: str = “985632” Output: 985632 Explanation: Given input is in string form and returned output is in integer form. Input: str = “123” Output: 123 Explanation: Given input is in string form and returned output is in integer form.

Approach: The idea is to use the ASCII value of the digits from 0 to 9 start from 48 – 57. Therefore, to change the numeric character to an integer subtract 48 from the ASCII value of the character will give the corresponding digit for the given character. 

Below is the implementation of the above approach: 

C




// C program for the above approach
#include <stdio.h>
#include <string.h>
  
// Function to convert string to
// integer without using functions
void convert(char s[])
{
    // Initialize a variable
    int num = 0;
    int n = strlen(s);
  
    // Iterate till length of the string
    for (int i = 0; i < n; i++)
  
        // Subtract 48 from the current digit
        num = num * 10 + (s[i] - 48);
  
    // Print the answer
    printf("%d", num);
}
  
// Driver Code
int main()
{
    // Given string of number
    char s[] = "123";
  
    // Function Call
    convert(s);
    return 0;
}


C++




// C++ program for the above approach
#include <iostream>
using namespace std;
  
// Function to convert string to
// integer without using functions
void convert(string s)
{
    // Initialize a variable
    int num = 0;
    int n = s.length();
  
    // Iterate till length of the string
    for (int i = 0; i < n; i++)
  
        // Subtract 48 from the current digit
        num = num * 10 + (int(s[i]) - 48);
  
    // Print the answer
    cout << num;
}
  
// Driver Code
int main()
{
    // Given string of number
    char s[] = "123";
  
    // Function Call
    convert(s);
    return 0;
}


Java




// Java program for the above approach
class GFG{
  
// Function to convert string to
// integer without using functions
public static void convert(String s)
{
      
    // Initialize a variable
    int num = 0;
    int n = s.length();
  
    // Iterate till length of the string
    for(int i = 0; i < n; i++)
  
        // Subtract 48 from the current digit
        num = num * 10 + ((int)s.charAt(i) - 48);
  
    // Print the answer
    System.out.print(num);
}
  
// Driver code
public static void main(String[] args)
{
    // Given string of number
    String s = "123";
  
    // Function Call
    convert(s);
}
}
  
// This code is contributed by divyeshrabadiya07


Python3




# Python3 program for the above approach
  
# Function to convert string to
# integer without using functions
def convert(s):
  
    # Initialize a variable
    num = 0
    n = len(s)
  
    # Iterate till length of the string
    for i in s:
  
        # Subtract 48 from the current digit
        num = num * 10 + (ord(i) - 48)
  
    # Print the answer
    print(num)
  
# Driver code
if __name__ == '__main__':
  
    # Given string of number
    s = "123"
  
    # Function Call
    convert(s)
  
# This code is contributed by Shivam Singh


C#




// C# program for the above approach
using System;
  
class GFG{
  
// Function to convert string to
// integer without using functions
public static void convert(string s)
{
      
    // Initialize a variable
    int num = 0;
    int n = s.Length;
  
    // Iterate till length of the string
    for(int i = 0; i < n; i++)
  
        // Subtract 48 from the current digit
        num = num * 10 + ((int)s[i] - 48);
  
    // Print the answer
    Console.Write(num);
}
  
// Driver code
public static void Main(string[] args)
{
      
    // Given string of number
    string s = "123";
  
    // Function call
    convert(s);
}
}
  
// This code is contributed by rock_cool


Javascript




// Function to convert string to
// integer without using functions
function convert(s) {
  
  // Initialize a variable
  let num = 0;
  let n = s.length;
  
  // Iterate till length of the string
  for (let i = 0; i < n; i++) {
  
    // Subtract 48 from the current digit
    num = num * 10 + (s.charCodeAt(i) - 48);
  
  }
  
  // Print the answer
  console.log(num);
  
}
  
// Driver code
let s = "123";
  
// Function Call
convert(s);
  
// This code is contributed by Prince Kumar


Output

123

Time Complexity: O(N), where N is the length of the given string. 

Auxiliary Space: O(1)

Approach: In the above approach we still used built-in functions len and chr. Below is solution with using any function and not using indices as well.

C++




#include <iostream>
#include <unordered_map>
  
using namespace std;
  
int strToInt(string s) {
  unordered_map<char, int> chrToInt = {{'1', 1}, {'2', 2}, {'3', 3}, {'4', 4}, {'5', 5},
                                       {'6', 6}, {'7', 7}, {'8', 8}, {'9', 9}, {'0', 0}};
  int i = 0;
  int minus = 0;
  int ifFloat = 0;
  string res = "";
  for (char ch : s) {
    if (ch == '-' && i == 0) {
      minus = 1;
    } else if (ch == '+' && i == 0) {
      i += 1;
    } else if (ch == '.') {
      if (ifFloat == 1) {
        throw "Value Error";
      }
      ifFloat = 1;
    } else if (chrToInt.count(ch)) {
      if (ifFloat == 0) {
        res += ch;
      } else {
        throw "Value Error";
      }
    } else {
      throw "Value Error";
    }
    i += 1;
  }
  int num = 0;
  for (char c : res) {
    num = num * 10 + chrToInt;
  }
  if (minus == 1) {
    num *= -1;
  }
  return num;
}
  
int main() {
  string inputArr[] = {"34.4.5", "-inf", "233.a", "# 567", "000234", ".023", "-23.78",
                       "36625276396422484242000000000000000", "a1a1a1", "10.00001", "", "-.23", "583.40000",
                       "0000", "10e2 ", "2×4"};
  string input2[] = {"+466", "+0.23", "101001", "0023", "4001.23", "40.834", "aaa", "abc234", "23.543abc", "–0.0",
                     "-0.0", "0.0", "222.2", "-+1323", "+-23"};
  int len1 = sizeof(inputArr) / sizeof(inputArr[0]);
  int len2 = sizeof(input2) / sizeof(input2[0]);
  for (int i = 0; i < len1; i++) {
    try {
      cout << strToInt(inputArr[i]) << endl;
    } catch (const char* msg) {
      cout << msg << endl;
    }
  }
  for (int i = 0; i < len2; i++) {
    try {
      cout << strToInt(input2[i]) << endl;
    } catch (const char* msg) {
      cout << msg << endl;
    }
  }
  return 0;
}


Java




import java.util.HashMap;
  
public class StrToInt
{
    
    // Function to convert string to integer without using functions
    public static int strToInt(String s) throws Exception {
        HashMap<Character, Integer> chrToInt = new HashMap<Character, Integer>();
        chrToInt.put('1', 1);
        chrToInt.put('2', 2);
        chrToInt.put('3', 3);
        chrToInt.put('4', 4);
        chrToInt.put('5', 5);
        chrToInt.put('6', 6);
        chrToInt.put('7', 7);
        chrToInt.put('8', 8);
        chrToInt.put('9', 9);
        chrToInt.put('0', 0);
  
        int i = 0;
        int minus = 0;
        int ifFloat = 0;
        String res = "";
  
        for (char ch : s.toCharArray()) {
            if (ch == '-' && i == 0) {
                minus = 1;
            } else if (ch == '+' && i == 0) {
                i += 1;
            } else if (ch == '.') {
                if (ifFloat == 1) {
                    throw new Exception("Value Error");
                }
                ifFloat = 1;
            } else if (chrToInt.containsKey(ch)) {
                if (ifFloat == 0) {
                    res += ch;
                } else {
                    throw new Exception("Value Error");
                }
            } else {
                throw new Exception("Value Error");
            }
            i += 1;
        }
  
        int num = 0;
        for (char c : res.toCharArray()) {
            num = num * 10 + chrToInt.get(c);
        }
        if (minus == 1) {
            num *= -1;
        }
        return num;
    }
  
    // Driver code
    public static void main(String[] args) {
        String[] inputArr = {"34.4.5", "-inf", "233.a", "# 567", "000234", ".023", "-23.78",
                             "36625276396422484242000000000000000", "a1a1a1", "10.00001", "", "-.23", "583.40000",
                             "0000", "10e2 ", "2×4"};
        String[] input2 = {"+466", "+0.23", "101001", "0023", "4001.23", "40.834", "aaa", "abc234", "23.543abc", "–0.0",
                           "-0.0", "0.0", "222.2", "-+1323", "+-23"};
  
        for (String s : inputArr) {
            try {
                System.out.println(strToInt(s));
            } catch (Exception e) {
                System.out.println("Value Error");
            }
        }
    }
}


Python3




# Python3 program for the above approach
  
# Function to convert string to
# integer without using functions
def strToInt(s):
  chrToInt = {‘1?: 1, ’2?: 2, ’3?: 3, ’4?: 4, ’5?: 5, ’6?: 6, ’7?: 7, ’8?: 8, ’9?: 9, ’0?: 0}
  i = 0
  minus = 0
  ifFloat = 0
  
  res = “”
  
  for char in s:
  if char ==-and i == 0:
  minus = 1
  i += 1
  
  elif char ==+and i == 0:
  i += 1
  
  elif char ==’.’:
  if ifFloat:
  raise ValueError
  ifFloat = 1
  i += 1
  
  elif char in chrToInt:
  if not ifFloat:
  res += char
  i += 1
  
  else:
  raise ValueError
  
  num = 0
  for c in res:
  num = num*10 + chrToInt
  
  if minus == 1:
  num *= -1
  
  return num
  
# Driver code
if __name__ == ‘__main__’:
  inputArr = [“34.4.5”, “-inf”, ”233.a”, ”  # 567?,”000234?,”.023?,”-23.78?,
                36625276396422484242000000000000000”, ”a1a1a1?, ”10.00001?, ””, ”-.23?, ”583.40000?,
                0000”, ”10e2 “, ”2×4”]
  input2 = [“+466?, ”+0.23?, ”101001?, ”0023?, ”4001.23?, ”40.834?, ”aaa”, ”abc234?, ”23.543abc”, ”–0.0?,
              -0.0?, ”0.0?, ”222.2?, ”-+1323?, ”+-23?]
  
  for s in inputArr:
    try:
      print(strToInt(s))
    except ValueError:
      print(“Value Error”)


C#




using System;
using System.Collections.Generic;
  
class StrToIntClass
{
// Function to convert string to integer without using functions
static int StrToInt(string s)
{
Dictionary<char, int> chrToInt = new Dictionary<char, int>(){
{'1', 1},
{'2', 2},
{'3', 3},
{'4', 4},
{'5', 5},
{'6', 6},
{'7', 7},
{'8', 8},
{'9', 9},
{'0', 0}
};
    int i = 0;
    int minus = 0;
    int ifFloat = 0;
    string res = "";
  
    foreach (char ch in s)
    {
        if (ch == '-' && i == 0)
        {
            minus = 1;
        }
        else if (ch == '+' && i == 0)
        {
            i += 1;
        }
        else if (ch == '.')
        {
            if (ifFloat == 1)
            {
                throw new Exception("Value Error");
            }
            ifFloat = 1;
        }
        else if (chrToInt.ContainsKey(ch))
        {
            if (ifFloat == 0)
            {
                res += ch;
            }
            else
            {
                throw new Exception("Value Error");
            }
        }
        else
        {
            throw new Exception("Value Error");
        }
        i += 1;
    }
  
    int num = 0;
    foreach (char c in res)
    {
        num = num * 10 + chrToInt;
    }
    if (minus == 1)
    {
        num *= -1;
    }
    return num;
}
  
// Driver code
static void Main(string[] args)
{
    string[] inputArr = {"34.4.5", "-inf", "233.a", "# 567", "000234", ".023", "-23.78",
                         "36625276396422484242000000000000000", "a1a1a1", "10.00001", "", "-.23", "583.40000",
                         "0000", "10e2 ", "2×4"};
    string[] input2 = {"+466", "+0.23", "101001", "0023", "4001.23", "40.834", "aaa", "abc234", "23.543abc", "–0.0",
                       "-0.0", "0.0", "222.2", "-+1323", "+-23"};
  
    foreach (string s in inputArr)
    {
        try
        {
            Console.WriteLine(StrToInt(s));
        }
        catch (Exception e)
        {
            Console.WriteLine("Value Error");
        }
    }
}
}


Javascript




// Function to convert string to integer without using functions
function strToInt(s) {
  const chrToInt = { '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
                     '6': 6, '7': 7, '8': 8, '9': 9, '0': 0 };
  let i = 0;
  let minus = 0;
  let ifFloat = 0;
  let res = '';
  for (let ch of s) {
    if (ch === '-' && i === 0) {
      minus = 1;
    } else if (ch === '+' && i === 0) {
      i += 1;
    } else if (ch === '.') {
      if (ifFloat === 1) {
        throw new Error('Value Error');
      }
      ifFloat = 1;
    } else if (chrToInt.hasOwnProperty(ch)) {
      if (ifFloat === 0) {
        res += ch;
      } else {
        throw new Error('Value Error');
      }
    } else {
      throw new Error('Value Error');
    }
    i += 1;
  }
  let num = 0;
  for (let c of res) {
    num = num * 10 + chrToInt;
  }
  if (minus === 1) {
    num *= -1;
  }
  return num;
}
  
const inputArr = ['34.4.5', '-inf', '233.a', '# 567', '000234', '.023', '-23.78',
                  '36625276396422484242000000000000000', 'a1a1a1', '10.00001', '', '-.23', '583.40000',
                  '0000', '10e2 ', '2×4'];
const input2 = ['+466', '+0.23', '101001', '0023', '4001.23', '40.834', 'aaa', 'abc234', '23.543abc', '–0.0',
                '-0.0', '0.0', '222.2', '-+1323', '+-23'];
for (let i = 0; i < inputArr.length; i++) {
  try {
    console.log(strToInt(inputArr[i]));
  } catch (err) {
    console.log(err.message);
  }
}
for (let i = 0; i < input2.length; i++) {
  try {
    console.log(strToInt(input2[i]));
  } catch (err) {
    console.log(err.message);
  }
}


Output

Value Error
Value Error
Value Error
Value Error
234
Value Error
Value Error
-1535836160
Value Error
Value Error
0
Value Error
Value Error
0
Value Error
Value Error


Last Updated : 13 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads