用递归实现String转Int

String转Int

#include
#include
using namespace std;
int stoi(string str, int &r, int i){
	if(i < str.length()-1){
		int t = 1+stoi(str,r,i+1);
		r += pow(10,t)*(str[i]-48);
		return t;
	}else{
		r += str[i]-48;
		return 0;
	}
}
int main(){
	string str = "12345";
	int res = 0;
	stoi(str,res,0);
	printf("%d",res);
	return 0;
}

stoi是一个递归函数,返回值是int


递归过程

仔细找找规律

"12345" 的长度为l = 5
stoi("123456",0,0)  i = 0, i< l-1 ->>> t = stoi("123456",0,1)  return t+1 = 5; ->>> res += pow(10,t)*(str[i]-48)  
stoi("123456",0,1)  i = 1, i< l-1 ->>> t = stoi("123456",0,2)  return t+1 = 4; ->>> res += pow(10,t)*(str[i]-48)  
stoi("123456",0,2)  i = 2, i< l-1 ->>> t = stoi("123456",0,3)  return t+1 = 3; ->>> res += pow(10,t)*(str[i]-48)  
stoi("123456",0,3)  i = 3, i< l-1 ->>> t = stoi("123456",0,4)  return t+1 = 2; ->>> res += pow(10,t)*(str[i]-48)  
stoi("123456",0,4)  i = 4, i< l-1 ->>> t = stoi("123456",0,5) return t+1 = 1; ->>> res += pow(10,t)*(str[i]-48)  
stoi("123456",0,5)  i = 5, i== l-1 ->>> return 0; ->>> res += str[i]-48

上面的代码实现功能的函数为 stoi ,调用规则 stoi(string,int,0);
string :待转化的string变量名
int :待存放int型的变量名,注意:int变量要初始化为0
0 :不用管,这是递归开始的状态

你可能感兴趣的:(c语言,递归法)