uacs2024

导航

复试C++15真题_程序设计2_递归_输入字符串倒序转整形

编写一个递归函数,功能为:输入一个字符串,输出一个整数值。例如输入  "1a2xcz3 4 ,5a!6"  ,  输出654321。

一开始想不明白怎么写递归,于是我写了迭代的函数。意识到,递归的过程就是实现了迭代的循环,而循环内的操作本质没有太大差别。于是就写出来了:

#include <iostream>
using namespace std;

//迭代版本
int toInt2(char str[]){
    int res = 0,jieshu = 1;
    for(int i = 0;str[i] != '\0';i++){
        if(str[i]>='0'&&str[i]<='9'){
            res = res + (str[i]-'0') * jieshu;
            jieshu *= 10;
        }
    }
    return res;
}

int toInt(char str[],int res,int jieshu){
    if(*str == '\0')    return res;  //迭代版本每一次执行循环前都要先判断是否到达字符串尾部
    else if(*str>='0'&&*str<='9'){
        res = res + (*str-'0') * jieshu;
        return toInt(++str,res,jieshu*10);  //通过对str的移动代替迭代版本的i
    }
    else{
        return toInt(++str,res,jieshu);  //既不是字符串尾也不是数字就要保留原来的数据,str向前移动
    }
    return res;
}
//递归版本
int toInt(char str[]){
    return toInt(str,0,1);
}

int main(){
    char str[] = "1a2xcz3 4 ,5a!6";  //654321
    cout << toInt2(str) << endl;
    cout << toInt(str) << endl;
}

至于怎么输入字符到字符数组,似乎比想象中的简单?这东西哪怕我输入20个字符也不报错,也照样输出全部字符,也不报错?

int main(){
    char str[10];
    cin >> str;
    cout << str << endl;
}

 

posted on 2024-03-20 20:42  ᶜʸᵃⁿ  阅读(5)  评论(0编辑  收藏  举报