0

0

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

PHPz

PHPz

发布时间:2023-09-07 12:49:17

|

1026人浏览过

|

来源于tutorialspoint

转载

adding one to number represented as array of digits in c program?

在这个部分,我们将看到一个有趣的问题。假设给定一个数字。我们需要将这个数字增加1。这是一个非常简单的任务。但是在这里,我们将把数字作为一个数组放置。该数字的每个数字都被放置为数组的一个元素。如果数字是512,那么它将被存储为{5, 1, 2}。而且我们还必须使用递归方法增加数字。让我们看看算法以获得清晰的思路。

算法

increment(arr, n, index) −

Trickle AI
Trickle AI

多功能零代码AI应用开发平台

下载
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 
#include 
#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

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
页面置换算法
页面置换算法

页面置换算法是操作系统中用来决定在内存中哪些页面应该被换出以便为新的页面提供空间的算法。本专题为大家提供页面置换算法的相关文章,大家可以免费体验。

404

2023.08.14

C++ 高级模板编程与元编程
C++ 高级模板编程与元编程

本专题深入讲解 C++ 中的高级模板编程与元编程技术,涵盖模板特化、SFINAE、模板递归、类型萃取、编译时常量与计算、C++17 的折叠表达式与变长模板参数等。通过多个实际示例,帮助开发者掌握 如何利用 C++ 模板机制编写高效、可扩展的通用代码,并提升代码的灵活性与性能。

10

2026.01.23

php远程文件教程合集
php远程文件教程合集

本专题整合了php远程文件相关教程,阅读专题下面的文章了解更多详细内容。

28

2026.01.22

PHP后端开发相关内容汇总
PHP后端开发相关内容汇总

本专题整合了PHP后端开发相关内容,阅读专题下面的文章了解更多详细内容。

21

2026.01.22

php会话教程合集
php会话教程合集

本专题整合了php会话教程相关合集,阅读专题下面的文章了解更多详细内容。

20

2026.01.22

宝塔PHP8.4相关教程汇总
宝塔PHP8.4相关教程汇总

本专题整合了宝塔PHP8.4相关教程,阅读专题下面的文章了解更多详细内容。

11

2026.01.22

PHP特殊符号教程合集
PHP特殊符号教程合集

本专题整合了PHP特殊符号相关处理方法,阅读专题下面的文章了解更多详细内容。

11

2026.01.22

PHP探针相关教程合集
PHP探针相关教程合集

本专题整合了PHP探针相关教程,阅读专题下面的文章了解更多详细内容。

8

2026.01.22

菜鸟裹裹入口以及教程汇总
菜鸟裹裹入口以及教程汇总

本专题整合了菜鸟裹裹入口地址及教程分享,阅读专题下面的文章了解更多详细内容。

52

2026.01.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号