题目概述:
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?
题目解析:
主要考察整数各个位数求和,当且仅当和小于10时输出。可能会走入整数转换为字符串的误区,直接使用取余(%)个位数相加即可,需要注意:
1.非负整数判断
2.输入0时输出0,输入10时输出1
3.至于O(1)时间复杂度考察数学公式:1 + (num-1) % 9
4.整数转换字符串可以类似思想:循环个位数转换reslut=num%10,num=num/10
我的代码:
推荐代码:
原文地址:https://blog.csdn.net/Eastmount/article/details/48294623
(By:Eastmount 2021-7-31 下午6点半 )