递归地将整数存储在数组中

时间:2018-03-07 18:38:41

标签: c++ arrays recursion integer

我有递归函数的问题。

我必须构建一个递归函数,它创建一个与给定数字的数字相对应的整数值数组。

例如,如果我输入一个像3562这样的数字,它应该是:

myArray[0] = 3
myArray[1] = 5
myArray[2] = 6
myArray[3] = 2

这是我的代码:

#include <iostream>
using namespace std;

int myFunction(int num, int lenOfNum);

int main(){
    int number;
    int lengthCount = 0;
    cout <<"Input numbers" << endl;
    cin >> number;
    int temp = number;
    for(; number != 0; number /= 10, lengthCount++);        
    number = temp;  
    cout << myFunction(number, lengthCount) << endl;            
}  

int myFunction(int num, int lenOfNum){
    int arr[lenOfNum];
    if(num > 0){
        for(int i = 0; i < lenOfNum; i++){
            arr[i] = num/=10;
            cout << "arr[" << i + 1 << " ]= " << arr[i] << endl;
        }
        return myFunction(num, lenOfNum);
    }
    else if(num == 0){
        return 0;   
    } else; 
}

3 个答案:

答案 0 :(得分:1)

您的代码的问题在于您在每个方法调用中调用int arr[lenOfNum],这简单地创建了一个数组,其中包含对可以存储lenOfNum整数的内存位置的新引用。

要解决这个问题,我们在main方法中声明数组并将其作为参数传递给函数。

int main() { 
    // somewhere in main after reading lenOfNum
    int arr[lenOfNum];
    // somewhere in main after declaring an array
    myFunction(arr, number, lengthCount - 1);
}

和myFunction为

void myFunction(int *arr, int num, int idx) {
    if (idx < 0) return;  // you've completed processing the num
    else if (num == 0) {
        arr[0] = 0;
        return;
    }

    arr[idx--] = num % 10;
    myFunction(arr, num / 10, idx);
}

答案 1 :(得分:0)

使用示例的向量和休息部分

#include <iostream>
using namespace std;

void myFunction(vector<int> &arr, int num, int lenOfNum){
    if (num < 0) {
        return;
    }
    else if (num == 0) {
        return;
    }
    int next_idx = lenOfNum - 1;
    int digit = num % 10;
    arr[next_idx] = digit;
    myFunction(arr, num / 10, next_idx);
}


int main(){
    int number;
    int lengthCount = 0;
    cout <<"Input numbers" << endl;
    cin >> number;
    int temp = number;
    for(; number != 0; number /= 10, lengthCount++);        
    number = temp;  

    auto arr = vector<int>(lengthCount, 0);
    myFunction(arr, number, lengthCount);
    for(int i = 0; i < arr.size(); i++){
         cout << "arr[" << i << " ]= " << arr[i] << endl;
    }
}  

答案 2 :(得分:0)

适用于正数

#include <vector>
#include <stdio.h>

std::vector<int> myFunction(int num)
{
  std::vector<int> ret;
  int irec = num / 10;
  if (irec > 0)
     ret = myFunction(irec);
  ret.push_back('0' + (num % 10));
  return ret;      
}

int main(int argc, char *argv[])
{
    std::vector<int> res = myFunction(539);
    for(unsigned int i = 0; i < res.size(); i++)
        printf("%c,", res[i]);
}