前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Baozi Training Leetcode Solution 258: Add Digits

Baozi Training Leetcode Solution 258: Add Digits

作者头像
包子面试培训
发布2019-08-01 11:05:24
3430
发布2019-08-01 11:05:24
举报
文章被收录于专栏:包子铺里聊IT包子铺里聊IT

Problem Statement

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:

代码语言:javascript
复制
Input: 38
Output: 2
Explanation: 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?

Problem link

Video Tutorial

You can find the detailed video tutorial here

  • Youtube
  • B站

Thought Process

Just do a simple brute force simulation. Unless you know what a digital root is, beforehand solving it in O(1) cannot collect any useful signals from the candidate.

The triple bar equal is quite interesting. It means congruence. E.g., if you have two exactly same figures but one is rotated or clock points to 13 and 1, they are considered congruence (just like 13 and 1 mod by 12 are equal). In our example, it's about the mod result, e.g.,

Side note:

I am sharing with everyone on this problem just to express how useless this problem is... Honestly if someone ask you to solve this problem in O(1) time in a real interview, rethink joining that company. If you are an interviewer, please do yourself a favor not asking your candidate to solve it in O(1). It's an okay question to ask as a warm up just to calm your candidate down for the brute force solution.

Solutions

Brute force

Keep summing the each digit until the final number is < 10

代码语言:javascript
复制
 1 public int addDigits(int num) {
 2         assert num >= 0;
 3 
 4         while (num / 10 > 0) {
 5             num = this.calDigitSum(num);
 6         }
 7         return num;
 8     }
 9 
10     private int calDigitSum(int num) {
11         int res = 0;
12 
13         while (num > 0) {
14             res += num % 10;
15             num = num / 10;
16         }
17         return res;
18     }

Time Complexity: O(N), N is the length of the digit

Space Complexity: O(1), No extra space is needed

Use the digital root formula

return (num - 1) % 9 + 1

Time Complexity: O(1)

Space Complexity: O(1)

References

  • Congruence
  • Digital Root
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 包子铺里聊IT 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem Statement
  • Video Tutorial
  • Thought Process
  • Solutions
    • Brute force
      • Use the digital root formula
      • References
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档