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

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

解法一、按照定义做,直到结果只剩1位数字。

class Solution {
public:
int addDigits(int num) {
int n = num;
while(n > )
{
int cur = ;
while(n)
{
cur += (n % );
n /= ;
}
n = cur;
}
return n;
}
};

解法二、套公式digital root

class Solution {
public:
int addDigits(int num) {
return num - * floor((num - ) / );
}
};

最新文章

  1. php报错 ----> Call to undefined function imagecreatetruecolor()
  2. 慕课网Java高并发秒杀学习
  3. 代码中access 的使用
  4. 转: 认识 HTTPS
  5. spring来了-05-JDBC
  6. MATLAB做主成分分析(PCA)
  7. 鸟哥笔记:syslogd:记录日志文件的服务
  8. ModelAndView使用方法
  9. MYSQL死锁
  10. 浅谈C#中的泛型
  11. CF 327E(Axis Walking-状态压缩Dp-lowbit的使用)
  12. mybatis---------insert,delete ,update的批量操作
  13. 2017 CVTE春招内推专场 C/C++软件开发岗笔试编程题
  14. Spring《错误集合,总结更新》
  15. Java高新技术 Myeclipse 介绍
  16. Springboot security cas整合方案-原理篇
  17. oracle中创建数据库用户,并授权
  18. net core体系-API-1Ocelot-(3)简单项目实战
  19. spring-boot 集成 log4j 记录日志
  20. 运用Zabbix实现内网服务器状态及局域网状况监控(5) —— Zabbix监控路由器

热门文章

  1. MindFusion Pack for ASP.NET发布v2013.R2
  2. inotify 心得
  3. 关闭Ubuntu 12.04的内部错误提示
  4. poj 1035 Spell checker
  5. 跟我一起学WCF(2)——利用.NET Remoting技术开发分布式应用
  6. Java Config 下的Spring Test方式
  7. Unity3D——相机跟随物体移动
  8. Hash与Map
  9. jenkins2 hello pipeline
  10. linux下安装小鹤双拼-鹤形