DMITRII’s Substack

Share this post

Leetcode daily # 26.04.2023

dmitriisamoilenko.substack.com

Leetcode daily # 26.04.2023

[258. Add Digits]

DMITRII SAMOILENKO
Apr 26, 2023
Share

26.04.2023

258. Add Digits easy

fun addDigits(num: Int): Int = if (num == 0) 0 else 1 + ((num - 1) % 9)
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
// 0 1 2 3 4 5 6 7 8 9 1  2  3  4  5  6  7  8  9  1  2  3  4  5  6  7  8  9  1  2  3  4  5  6  7  8  9  1  2
// 0 [1..9] [1..9] [1..9] ...

blog post

Thanks for reading DMITRII’s Substack! Subscribe for free to receive new posts and support my work.

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/192

Intuition

Observing the pattern:

// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
// 0 1 2 3 4 5 6 7 8 9 1  2  3  4  5  6  7  8  9  1  2  3  4  5  6  7  8  9  1  2  3  4  5  6  7  8  9  1  2
// 0 [1..9] [1..9] [1..9] ...

There is a repeating part of it: [1..9], so we can derive the formula.

Approach

It is just an array pointer loop shifted by 1.

Complexity

  • Time complexity:
    O(1)

  • Space complexity:
    O(1)

Thanks for reading DMITRII’s Substack! Subscribe for free to receive new posts and support my work.

Share
Previous
Next
Comments
Top
New

No posts

Ready for more?

© 2023 DMITRII SAMOILENKO
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing