Sum of all numbers in an integer

It is a common interview question that is frequently asked.
In this the interviewer is looking for some basics like iterating the loops etc.

If given integer is 987 then the output of the program should return 24.
Let's look at its algorithm, dry run, implementation, and complexity.

Algorithm:
  1. Step 1: Declare a variable “a” and initialize it with the given value ‘987’.
    1. a = 987;
  2. Step 2: Assign the integer value to a temporary variable for further operation on it. 
    1. temp = 987;
  3. Step 3: Declare a variable “sum” to assign the final sum and initialize it with 0(zero). 
    1. sum = 0;
  4. Step 4: Using while loop, Iterate the next two steps until the variable temp becomes 0(zero).
  5. Step 5: Get the rightmost digit of the number with the modulus/remainder ‘%’ operator. Add the rightmost digit to sum variable.
  6. Step 6: Divide the number by 10 with ‘/’ operator.
  7. Step 7: Print the sum value ‘24’.

 Dry Run:
Iteration 1: Start the loop
temp = 987; temp != 0 -> Condition true
sum = 0 + (987 % 10); (step 5: sum = sum + temp % 10)
sum = 0 + 7;
sum = 7;
temp = 987 / 10; (step 6: temp = temp / 10)
temp = 98;
Iteration 2:
temp = 98; temp != 0 -> Condition true
sum = 7 + (98 % 10);
sum = 7 + 8;
sum = 15;
temp = 98 / 10;
temp = 9;
Iteration 3:
temp = 9; temp != 0 -> Condition true
sum = 15 + (9 % 10);
sum = 15 + 9;
sum = 24;
temp = 9 / 10;
temp = 0;
Iteration 4:
temp = 0; temp !=0 -> Condition false.
Terminate the loop.

Sample output: 
Sum = 24



Implementation:
#include <iostream>

#include <conio.h>

int main()
{
int a = 987;
int temp = a;
int sum = 0;
int temp2 = 0;


while (temp != 0)
{
sum = sum + temp % 10;
temp2 = sum;
temp = temp / 10;
}


std::cout << "Sum:" << sum << std::endl;
getch();
return 0;

}

Algorithm complexity
O(log n)


No comments:

Post a Comment

NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...