在C程序中以数字数组形式表示的数字加1?
在本节中,我们将看到一个有趣的问题。假设给出一个数字。我们必须将此数字增加1。这是非常简单的任务。但是在这里,我们将数字放置为数组。该数字的每个数字都作为数组的元素放置。如果数字是512,则它将存储为{5,1,2}。而且我们还必须使用递归方法来增加数量。让我们看一下获得清晰思路的算法。
算法
增量(arr,n,索引)-
Initially the default value of index is 0
begin
if index < n, then
if arr[index] < 9, then
arr[index] := arr[index] + 1
else
arr[index] := 0
increment(arr, n, index + 1)
end if
if index = n, then
arr[n] := 1
n := n + 1
end if
end示例
#include <iostream>
#include <cmath>
#define MAX 20
using namespace std;
void increment(int num_arr[], int &n, int index = 0){
if(index < n){
if(num_arr[index] < 9){ //if digit is less than 9, add 1
num_arr[index]++;
}else{ //otherwise increase number recursively
num_arr[index] = 0;
increment(num_arr, n, index+1);
}
}
if(index == n){
num_arr[n] = 1; //add extra carry
n++; //increase n
}
}
void dispNumber(int num_arr[], int n){
for(int i = n-1; i>= 0; i--){
cout << num_arr[i];
}
cout << endl;
}
int numToArr(int num_arr[], int number){
int i = 0;
int n = log10(number) + 1;
for(int i = i; i< n; i++){
num_arr[i] = number % 10;
number /= 10;
}
return n;
}
main() {
int number = 1782698599;
int num_arr[MAX];
int n = numToArr(num_arr, number);
cout << "Initial Number: "; dispNumber(num_arr, n);
increment(num_arr, n);
cout << "Final Number: "; dispNumber(num_arr, n);
}输出结果
Initial Number: 1782698599 Final Number: 1782698600
热门推荐
6 祝福语简短古诗词
10 姐姐女儿结婚祝福语简短
11 幼儿狗年祝福语大全简短
12 小姨生日祝福语简短独特
13 春天变冷祝福语简短
14 订婚新发言简短祝福语
15 祝福语大全简短6个
16 开店大吉文案祝福语简短
17 宝宝周岁敬酒祝福语简短
18 八十大寿简短祝福语