c程序实现整数转换为字符串
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 (string, Eg. "1234")
输入格式:数字字符串(字符串,例如“ 1234”)
Output format: Corresponding integer (int, Eg. 1234)
输出格式:对应的整数(整数,例如1234)
Sample Input 1: "1231"
样本输入1: “ 1231”
Sample Output 1: 1231
样本输出1: 1231
Sample Input 1: "12567"
样本输入1: “ 12567”
Sample Output 1: 12567
样本输出1: 12567
Explanation:
说明:
In this question, we can solve it recursively. We start from unit’s digit and recursively shift to the last digit. After that we keeping on multiplying it by 10 and adding the number of present digit and return it. On completing the recursion it will return the number in integers.
在这个问题上,我们可以递归解决。 我们从单位的数字开始,然后递归地移到最后一个数字。 之后,我们继续将其乘以10,然后加上当前位数并返回。 完成递归后,它将返回整数形式的数字。
Algorithm:
算法:
STEP 1: Declare a recursive function ‘stringToNumber ‘with parameters (int arr[] , int len)
步骤1:使用参数声明一个递归函数'stringToNumber'(int arr [],int len)
STEP 2: Base Case: if (len == 0), convert the character into number and return it.
步骤2:基本情况:如果(len == 0),则将字符转换为数字并返回。
STEP 3: Recursive Case: Convert the character into number and store it in variable a.
步骤3:递归的情况:将字符转换为数字并将其存储在变量a中。
STEP 4: return a + 10 *stringToNumber(arr, len -1)
步骤4:传回+ 10 * stringToNumber(arr,len -1)
Example:
例:
Input = "23"
First Traversal = 2,
Second Traversal = 20 + 3,
Result = 23
C++ program:
C ++程序:
#include <bits/stdc++.h>
using namespace std;
//To find length of the string
int length(char input[]){
int len = 0;
for(int i =0;input[i] != '\0';i++){
len++;
}
return len;
}
//Helper Function
int stringToNumber(char input[], int last){
//Base Case
if(last == 0){
return input[last] - '0';
}
//Recursive Call
int smallAns = stringToNumber(input,last-1);
int a = input[last] - '0';
return smallAns * 10 + a;
}
//Recursive Function
int stringToNumber(char input[]){
int len = length(input);
return stringToNumber(input,len-1);
}
int main(){
char input[50];
cout<<"Enter Input"<<endl;
cin>>input;
cout<<"The output/number is ";
cout<<stringToNumber(input)<<endl;
return 0;
}
Output
输出量
Enter Input
1234
The output/number is 1234
翻译自: https://www.includehelp.com/cpp-programs/convert-a-string-of-number-to-integer.aspx
c程序实现整数转换为字符串