TCS Coding Practice Question | Sum of Digits of a number
Input: num = 687 Output: 21 Input: num = 12 Output: 3
- Since the number is entered as Command line Argument, there is no need for a dedicated input line
- Extract the input number from the command line argument
- This extracted number will be in string type.
- Convert this number into integer type and store it in a variable, say num
- Declare a variable to store the sum and set it to 0
- Repeat the next two steps till the number is not 0
- Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
- Divide the number by 10 with help of ‘/’ operator
- Print or return the sum
Time complexity: O(logn)
Auxiliary Space: O(1)
My Personal Notes arrow_drop_up