Similar Problems

Similar Problems not available

Encode Number - Leetcode Solution

Companies:

LeetCode:  Encode Number Leetcode Solution

Difficulty: Medium

Topics: math string bit-manipulation  

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

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

Solution: The solution to this problem can be divided into two steps:

  1. Calculate the sum of all digits
  2. Repeat the above step until only one digit is left

Step 1: To calculate the sum of all digits, we can use the following approach: a. Extract the last digit from the given number b. Add the extracted digit to a variable sum c. Remove the last digit from the given number

The above set can be repeated until the given number becomes zero. At the end, we will have the sum of all digits of the given number.

Step 2: To repeat the above step until only one digit is left, we can use a while loop. We will keep repeating the above step until the sum of digits becomes less than 10.

Here is the Python code for the above approach:

class Solution: def addDigits(self, num: int) -> int: # Step 1 while num >= 10: # Extract last digit and add to sum sum = 0 while num > 0: sum += num % 10 num //= 10 num = sum # Step 2 return num

Time Complexity: O(logn) Space Complexity: O(1)

The above approach has a time complexity of O(logn) and a space complexity of O(1).

Encode Number Solution Code

1