[easy]258. Add Digits

一道题目,将位数累加的计算。
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.
Follow up:Could you do it without any loop/recursion in O(1) runtime?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful.

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

注意,9能被整除的时候返回值是9

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,229评论 0 13
  • 最近在整理书橱的时候,发现一大堆不再会去看的书,于是在群里发了一个消息,问大家有没有想要借书的,没想到一群人要,所...
    小神同学阅读 708评论 0 0
  • 深秋的夜晚, 一只可怜的猴, 在主人的鞭挞之下, 唯唯诺诺地戏着, 而无知者的阵阵笑声, 让这个夜变得更黑。
    刘露灿阅读 4,536评论 13 17
  • 正月十五这天,家家户户早早便吃过年饭,坐等夜幕降临,这一刻人们期待了许久但等待的却十分耐心,因为这天是正月的十五,...
    羊一豪阅读 4,233评论 0 1

友情链接更多精彩内容