« String to integer recursively
Problem
Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer.
Input format :
Numeric string S (string, Eg. "1234")
Output format :
Corresponding integer N (int, Eg. 1234)
Constraints :
0 <= |S| <= 9
where |S| represents length of string S.
Sample Input 1 :
00001231
Sample Output 1 :
1231
Sample Input 2 :
12567
Sample Output 2 :
12567
Solution
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314int length(char input[])15{16 int len = 0;17 for (int i = 0; input[i] != '\0'; i++)18 {19 len++;20 }21 return len;22}2324int stringToNumber(char input[], int len)25{26 if (len == 1)27 {28 return (input[0] - '0');29 }30 int x = stringToNumber(input + 1, len - 1);31 x = x + (pow(10, len - 1) * (input[0] - '0'));32 return x;33}3435int stringToNumber(char input[])36{37 int len = length(input);38 int x = stringToNumber(input, len);39 return x;40}4142int main()43{44 char input[50];45 cin >> input;46 cout << stringToNumber(input) << endl;47 return 0;48}