Skip to content

Instantly share code, notes, and snippets.

@adamcee
Created October 7, 2025 14:17
Show Gist options
  • Select an option

  • Save adamcee/bc197643418aa1e0e8c98e82b60e5768 to your computer and use it in GitHub Desktop.

Select an option

Save adamcee/bc197643418aa1e0e8c98e82b60e5768 to your computer and use it in GitHub Desktop.

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Leetcode: Add Digits

Problem

https://leetcode.com/problems/add-digits/description/?envType=problem-list-v2&envId=prshgx6i

Example 1:

Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. Example 2:

Input: num = 0 Output: 0

Constraints:

0 <= num <= 231 - 1

Adam's Pseudocode

    INPUT: What sort of data goes into my program?
      - integer
      What kind of integer?
        - Negative int? NOT NEGATIVE
        - Zero - yes
            - edge case
        - How big? Big. I'm gonna worry about this later.

    OUTPUT: What my program need return?
    EDGE CASES: "Gotchas" - special numbers or values that aren't obvious

    Write down the logic in plain English

    Come up with some additional examples and work thru them "on paper"
    Get it working for the simplest examples first.
    THEN worry about the harder scenarios, or efficiency

    Examples:
        - 12
            12 ---> 1 + 2 = 3 ---> DONE
        - 9
            9 --> 9 DONE
        - 101
            101 ---> 1 + 0 + 1 = 2 
        - 9999
            9999 ----> 9 + 9 + 9 + 9 = 36 ---> 3 + 6 = 9 

    Pseudocode:
        LOOP:
            IF num is only 1 digit long, return it.
            OTHERWISE
                - break num into digits
                - add all the digits together
                - repeat the loop

Problem-solving guides:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment