[LeetCode] Add Digits
Well, if you have no idea of other methods, try to compue the result for all the numbers ranging from 1 to 20 and then you will see the regularity. After you find it, this problem just needs 1-line code.
I write the following code.
1 class Solution { 2 public: 3 int addDigits(int num) { 4 return num - (num - 1) / 9 * 9; 5 } 6 };
This link writes anther more elegant one.
class Solution { public: int addDigits(int num) { return (num - 1) % 9 + 1; } };
However, both of them cannot be used in Python since Python says that -1 % 9 = 8 and -1 / 9 = -1. Both the codes above will give a wrong answer for input 0. So you have to handle it separately.
1 class Solution: 2 # @param {integer} num 3 # @return {integer} 4 def addDigits(self, num): 5 return (num - 1) % 9 + 1 if num else 0
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步