Leetcode#258. Add Digits (数字根)
来源:互联网 发布:淘宝上伊芙丽假货多吗 编辑:程序博客网 时间:2024/06/11 21:51
声明:题目解法使用c++和Python两种,重点侧重在于解题思路和如何将c++代码转换为python代码。
题目
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?
题意
给你一个非负整数,通过重复相加直至得到一位数。
程序要求不能使用循环/递归,且时间复杂度为O(1)。
思路
前方高能注意,不能使用循环 or 递归。而且要求时间复杂度为O(1),暂时没有思路,看一下提示有没有有价值的信息。
前三条基本没用,最后一条:
You may find this Wikipedia article useful.
打开维基百科原来这是一道数字根的题目,用到的公式是同余式:
公式的文字意思:0的数字根为0,9的倍数的数字根为9,其他自然数的数字根为自然数除以9的余数。
上述公式也可以简单表述为:
自然数的数字根为自然数减去1除以9的余数加上1。
维基百科证明:https://en.wikipedia.org/wiki/Digital_root#Congruence_formula
所以,这道题就很好解决啦。
class Solution {public: int addDigits(int num) { /*公式一: if(num == 0) return 0; else if(num % 9 == 0) return 9; else return (num)%9; */ //公式二 return 1 + ((num - 1) % 9); }};
Github本题题解:https://github.com/xuna123/LeetCode/blob/master/Leetcode%23258.%20Add%20Digits.md
- Leetcode#258. Add Digits (数字根)
- 关于数字根(LeetCode Add Digits)
- LeetCode oj 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
- 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
- HTML5的语法和新属性
- 快速幂
- ral2html-寄存器文档工具
- 命令行参数的应用
- H5——canvas——动态时钟
- Leetcode#258. Add Digits (数字根)
- 设计模式之代理模式
- 月亮?是啊,今晚的月亮真美啊。
- xshell连接VM虚拟机上下左右及退格键不正常问题
- 双边滤波算法原理
- 【二进制划分集合 最短路】HDU6166 Senior Pan
- SpringMVC详解(二)------详细架构
- RecyclerView的学习
- ros 机器人操作系统 安装