[Leetcode从零开刷]258. Add Digits
来源:互联网 发布:vb九九乘法表左上三角 编辑:程序博客网 时间:2024/06/06 00:36
题目来源leetcode
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?
翻译:
给你一个非负整数,重复相加它的每个数字,直到结果只剩一个数字。举例:数字38–>3+8=11–>1+1=2–>结果就是返回2。
追加的要求就是运算速度要块O(1),不用递归。
解题:(我的方法比较笨,先看看到底是怎么输出的找规律)
先举例子枚举法:
0 –>0
1 –>1
2 –>2
3 –>3
4 –>4
5 –>5
6 –>6
7 –>7
8 –>8
9 –>9
10 –>1
…
18 –>9
19 –>1
20 –>2
…
27 –>9
28 –>1
我们发现数字的返回非常有规律基本就是从1到9的轮回。每到9的整数倍时即是9,不然返回的值均是此数除以9的余数。
所以有如下代码:
cpp:
class Solution {public: int addDigits(int num) { if(num == 0) return 0; else return (num-1)%9 +1; }};
阅读全文
0 0
- [Leetcode从零开刷]258. Add Digits
- 【LeetCode从零单刷】Add Digits
- 【LeetCode】258.Add Digits
- LeetCode 258. Add Digits
- LeetCode : 258. Add Digits
- leetCode 258. Add Digits
- LeetCode 258. Add Digits
- 258. Add Digits LeetCode
- LeetCode 258. Add Digits
- LeetCode 258. Add Digits
- leetcode 258. Add Digits
- [LeetCode]258. Add Digits
- LeetCode 258. Add Digits
- <LeetCode>258. Add Digits
- leetcode--258. Add Digits
- LeetCode 258. Add Digits
- LeetCode *** 258. Add Digits
- Leetcode 258. Add Digits
- python IDLE 背景修改 IDLE (Python GUI)
- svn的安装、常用操作和STS搭建SVN过程
- GPU高性能编程CUDA实战-代码
- asp.net core 实现一个简单的仓储
- 国超香港站群服务器为您解决企业网站加速解决方案
- [Leetcode从零开刷]258. Add Digits
- js实现点击置顶
- git笔记
- jQuery 教程 1
- Java 作业 1125/1126
- 12.1
- android-系统功能权限调用
- 深入浅出Standard I/O Library
- springboot跑批