c程序实现整数转换为字符串_C ++程序将数字字符串转换为整数

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:

算法:

  1. STEP 1: Declare a recursive function ‘stringToNumber ‘with parameters (int arr[] , int len)

    步骤1:使用参数声明一个递归函数'stringToNumber'(int arr [],int len)

  2. STEP 2: Base Case: if (len == 0), convert the character into number and return it.

    步骤2:基本情况:如果(len == 0),则将字符转换为数字并返回。

  3. STEP 3: Recursive Case: Convert the character into number and store it in variable a.

    步骤3:递归的情况:将字符转换为数字并将其存储在变量a中。

  4. 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程序实现整数转换为字符串

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值