博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]--258. Add Digits
阅读量:7234 次
发布时间:2019-06-29

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

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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

挺简单的一道题。

public int addDigits(int num) {        if (num / 10 == 0)            return num;        int sum = 0;        while (true) {            sum += num % 10;            num = num / 10;            if (num == 0) {                if (sum / 10 == 0)                    return sum;                num = sum;                sum = 0;            }        }    }

发人深省吧

1.逐位相加直到小于10

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

2.通过输入距离来发现规律

123456789 10 11 12 13 14 15

123456789 1 2 3 4 5 6

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

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

你可能感兴趣的文章
[译] 利用 Python 中的 Bokeh 实现数据可视化,第一部分:入门
查看>>
Vue教程14:配置子路由
查看>>
手牵手教你写 Vue 插件
查看>>
从零开始写项目第三篇【登陆注册模块】
查看>>
Hibernate的HQL语句参数异常IllegalArgumentException
查看>>
由《寻秦记》说代理模式(静态,动态,CGLib)
查看>>
04、Python 系列之 python 的基础知识
查看>>
猫客页面内组件的动态化方案-Tangram
查看>>
CTF中比较好玩的stego
查看>>
一起撸个朋友圈吧(step5) 控件篇(评论popup上)
查看>>
CAS源码分析
查看>>
uni-app 1.4 发布,一套代码,发行小程序(微信/支付宝/百度)、H5、App多个平台...
查看>>
移动端 IP 优选方案
查看>>
聊聊flink TaskManager的managed memory
查看>>
聊聊resilience4j的CircuitBreaker
查看>>
【广州-互联网-Node.js招聘】
查看>>
Android程序员面试会遇到的算法(part 1 关于二叉树的那点事) 附Offer情况
查看>>
SpaceVim - 打造 Java 开发环境
查看>>
[App探索]JSBox中幽灵触发器的实现原理探索
查看>>
HTML5新特性教程
查看>>