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 = 111 + 1 = 2. Since 2 has only one digit, return it.

分析一:最简单的循环方法

class Solution {
public:int addDigits(int num) {while (num / 10 != 0) {int temp = 0;while (num != 0) {temp += num % 10;num /= 10;}num = temp;}return num;}
};

分析二:参考https://leetcode.com/discuss/52122/accepted-time-space-line-solution-with-detail-explanations

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

转载于:https://www.cnblogs.com/vincently/p/4803875.html

[LeetCode] Add Digits相关推荐

  1. leetcode Add Digits

    题目连接 https://leetcode.com/problems/add-digits/ Add Digits Description Given a non-negative integer n ...

  2. [LeetCode] Add Digits - 数字各个位数求和

    题目概述: Given a non-negative integer num, repeatedly add all its digits until the result has only one ...

  3. LeetCode Add Digits(计算数位的和)

    题意:给出一个数,求将其各位数相加起来后的和,直到小于10 思路:参考https://en.wikipedia.org/wiki/Digital_root 代码如下: public class Sol ...

  4. Leetcode刷题记录[python]——258 Add Digits

    一.前言 做这题有个小收获,关于Digital root的解法,有个极方便的小公式: 二.题258 Add Digits Given a non-negative integer num, repea ...

  5. LeetCode Add Two Numbers II(栈)

    问题:给出两个链表表示的整数,求其和 思路:因为链表的第一个结点是最高位,最后一个结点是最低位.先将两个链表放入两个栈中.然后从两个栈中取出元素,从低到高位相加. 具体代码参考: https://gi ...

  6. LeetCode Add and Search Word - Data structure design(字典树)

    问题:设计一个支持addWord,search查询的数据结构,要求search支持.正则查询 思路:使用Trie数据结构,在匹配.时,从子结点中选取可行的一个继续匹配下一个字符,主要思路是基于递归 具 ...

  7. [leetcode][math] Add Digits

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

  8. LeetCode之Add Digits

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

  9. LeetCode 258. Add Digits

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

最新文章

  1. Java 程序员如何使用 Shiro 框架
  2. Docker容器间Link单向通信
  3. 如何选择正确的HTTP状态码
  4. spring bean依赖与配置
  5. spring的aop_Spring AOP 小结
  6. FDR错误发现率-P值校正学习
  7. opengl画的弧线 为什么有一个半径_6个1画生日蛋糕,也太简单啦【图文+视频教程】...
  8. android 移植 距离感应,Android sensors移植文档
  9. python for 循环中使用星号(*),实现分组展开列表
  10. SpringMVC jdbcTemplate中queryForObject以及queryForList返回映射实体使用
  11. docker 部署Java项目
  12. MySQL 数据库崩溃(crash)的常见原因和解决办法---发表到 《数据和云》 公众号
  13. html鼠标经过图片有浮起效果,CSS实现鼠标滑过卡片上浮效果的示例
  14. transition过渡的基本使用
  15. ESP8266便携式物联网时钟(硬件篇) 代号:喵
  16. 关于background背景和img图片
  17. Oracle表空间时间点恢复技术TSPITR
  18. 全国应用计算机水平考试,全国计算机应用水平考试
  19. 【备忘】Mongodb/Redis/HBase NoSql视频教程2017数据库自学教程
  20. 都说打印机又笨又丑 这一回联想小新给你好看!

热门文章

  1. 爱情神话:庄妃用美色套牢洪承畴之谜
  2. heroku_了解如何使用Heroku部署全栈Web应用程序
  3. react 监听组合键_投资组合中需要的5个React项目
  4. paypal提现软件_PayPal软件工程师生命中的一天
  5. react绑定this_React绑定模式:处理“ this”的5种方法
  6. javascript模块_JavaScript模块第2部分:模块捆绑
  7. Spring Cloud应用开发(四:服务容错保护)
  8. 【Linux学习笔记】 - 什么是Linux?
  9. 用计算机的英语造句process,process的用法总结大全
  10. UI培训教程分享:APP启动页UI界面设计