ホームページ  >  記事  >  バックエンド開発  >  Cプログラムで数字の配列として表される数値に1を加算しますか?

Cプログラムで数字の配列として表される数値に1を加算しますか?

PHPz
PHPz転載
2023-09-07 12:49:17986ブラウズ

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プログラムで数字の配列として表される数値に1を加算しますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。