將一個數字表示為 C 語言陣列中數字時遞增一
在這一部分中,我們將看到一個有趣的問題。假設給定一個數字。我們必須將此數字增加 1。這是一個非常簡單的問題。但這裡我們將把數字表示為陣列。該數字的每個數字都將放置為陣列的元素。如果數字為 512,則它將儲存為 {5, 1, 2}。而且我們還必須使用遞迴方法來增加此數字。讓我們看看演算法來獲取明確的想法。
演算法
increment(arr, n, index) −
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP