【LeetCode】258. Add Digits (2 solutions)
2024-08-29 16:06:56
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 = 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?
解法一、按照定义做,直到结果只剩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 - ) / );
}
};
最新文章
- php报错 ---->; Call to undefined function imagecreatetruecolor()
- 慕课网Java高并发秒杀学习
- 代码中access 的使用
- 转: 认识 HTTPS
- spring来了-05-JDBC
- MATLAB做主成分分析(PCA)
- 鸟哥笔记:syslogd:记录日志文件的服务
- ModelAndView使用方法
- MYSQL死锁
- 浅谈C#中的泛型
- CF 327E(Axis Walking-状态压缩Dp-lowbit的使用)
- mybatis---------insert,delete ,update的批量操作
- 2017 CVTE春招内推专场 C/C++软件开发岗笔试编程题
- Spring《错误集合,总结更新》
- Java高新技术 Myeclipse 介绍
- Springboot security cas整合方案-原理篇
- oracle中创建数据库用户,并授权
- net core体系-API-1Ocelot-(3)简单项目实战
- spring-boot 集成 log4j 记录日志
- 运用Zabbix实现内网服务器状态及局域网状况监控(5) —— Zabbix监控路由器