首页  >  文章  >  后端开发  >  在 C 程序中将数字加一表示为数字数组?

在 C 程序中将数字加一表示为数字数组?

PHPz
PHPz转载
2023-09-07 12:49:17987浏览

Adding one to number represented as array of digits in C Program?

在这个部分,我们将看到一个有趣的问题。假设给定一个数字。我们需要将这个数字增加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

以上是在 C 程序中将数字加一表示为数字数组?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除