博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 258. Add Digits两种方法
阅读量:4186 次
发布时间:2019-05-26

本文共 828 字,大约阅读时间需要 2 分钟。

/******************************

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

********************************************/
参考别的程序,思想为:

he problem, widely known as digit root problem, has a congruence formula:

For base b (decimal case b = 10), the digit root of an integer is:

dr(n) = 0 if n == 0

dr(n) = (b-1) if n != 0 and n % (b-1) == 0
dr(n) = n mod (b-1) if n % (b-1) != 0
or

dr(n) = 1 + (n - 1) % 9

Note here, when n = 0, since (n - 1) % 9 = -1, the return value is zero (correct).

int addDigits(int num) {        return 1 + (num - 1) % 9;    }

自己的程序,容易理解:

int addDigits(int num) {       while (num>9)            num=num/10+num%10;        return num;    }

转载地址:http://jvdoi.baihongyu.com/

你可能感兴趣的文章
ATS名词术语(待续)
查看>>
ATS缓存相关话题
查看>>
ATS中的RAM缓存简介
查看>>
CDN和Web Cache领域相关的经典书籍推荐
查看>>
在Oracle VM VirtualBox中如何安装64位虚拟机系统
查看>>
安装和使用Oracle VM VirtualBox中的要点,注意事项和遇到的问题
查看>>
ATS上的hosting.config和volume.config文件解读
查看>>
将日志中的指定字段对齐显示输出
查看>>
Linux上chown命令的高级用法
查看>>
利用sort对多字段排序
查看>>
Windows 10完美识别3TB硬盘实录
查看>>
在CentOS 6.x上安装luajit 2.0.4
查看>>
Linux下使用diff和patch制作及打补丁(已经实践可行!)
查看>>
ThinkPad T420更换SSD实录
查看>>
在Ubuntu 16.04.1 LTS上安装ats 5.3.2
查看>>
在CentOS 6.8 x86_64上安装ATS 6.2.1实录
查看>>
在CentOS 6.9 x86_64上玩转OpenResty 1.13.6.1中的resty-cli模块
查看>>
Spring中的Bean是有生命周期
查看>>
FreeMarker是一个用Java语言编写的模板引擎
查看>>
Markdown的语法简洁明
查看>>