[258]Add Digits
来源:互联网 发布:英语看图识音软件 编辑:程序博客网 时间:2024/04/30 10:38
【题目描述】
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.
【思路】
无
【代码】class Solution {public: int addDigits(int num) { int sum=0; if(num<=9) return num; sum=getsum(num); while(sum>=10){ sum=getsum(sum); } return sum; } int getsum(int n){ int ans=0; while(n){ ans+=n%10; n=n/10; } return ans; }};
在discuss里看到一种纯数学的方法,可惜并米有效率高点还是要耗时8ms。。不过贴上去借鉴一下。。
class Solution {public: int addDigits(int num) { return (num - 1) % 9 + 1; }};
0 0
- [258] Add Digits
- 258 Add Digits
- leetcode 258: Add Digits
- 258Add Digits - LeetCode
- leetCode #258 Add Digits
- 258-e-Add Digits
- 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
- 258 - Add Digits
- LeetCode 258 : Add Digits
- 【LeetCode】258 Add Digits
- Leetcode - 258 - Add Digits
- leetcode 258 :Add Digits
- 软件公司
- HTTP协议详解----HTTP消息
- JVM中类加载的机制
- 【大话设计模式】全局把握篇
- hustoj的永久pending 与 永久Running & Judging解决
- [258]Add Digits
- 安装vmware-tools遇The path "" is not a valid path to the 3.8.13-44.1.1.el6uek.x86_64 kernel问题解决
- [精华] 前段时间arch/i386/kernel/head.S注解
- CF#323-DIV2-D. Once Again-暴力贪心LIS
- HDU 5495 LCS (置换群)
- 《TCP/IP详解 卷一:协议》读书笔记--RARP:逆地址解析协议
- 详解ThreadLocal模式
- Ubuntu源问题(换源软件源更新源)
- tomcat的详细安装步骤