leetcode- 258 add digits

 in this problem statement there given positive integer n. we need to find the single digit of the number by adding the number digits in first iteration it get again double digit/ triple digit number again we sum the all individual digits and again check the condition, so it takes nested for (or) while loop so this problem has so many optimised to solve this one of the method is using one for loop and one while loop both are separtely not in inside 

input: num= 38

output:2

explanation: the process is

38--> 3 + 8-->11

11--> 1 + 1--> 2

this is code in C++:

class Solution {
public:
    int addDigits(int num) {
        int n=num;
        int k;
        int sum=0;
        while(n>0){
        sum+=n%10;
        n=n/10;
        }
        while(sum>=10){
        sum=(sum-10)+1;
        }
        return sum;
    }
};

  this is one type of approuch to solve this it submitted in Runtime: 0ms and memory usage: 8.3Mb

explination of code first for is used to sum of all digits by modules 10 it get last element and by n=n/10

 dividing  10 its last element removed. let take n=138 by n%10 its get 8 and by dividing /10 it removes the last element that will be store in same variable(n) to condition false to break the loop by not placing the n=n/10; in code it runs infinte times because there is false condition to break the loop

then the sum of 138 is 1+3+8= 12 that value store in sum. In second while loop operates when ever the number is greather than or equal to 10 only in sum=(sum-10)+1;h this operation is main to the entire operation based on this it self only the sum=12 right so int above that we follow (12-10)+1 -->2+1-->3

the finally answer of that that sum again chech the condition of while it falses so it break the loop and finally return the sum that get output

there is anther method in single line its also acceptable its time complexity O(1):

class Solution {
public:
    int addDigits(int num) {
        return (num-1)%9+1;
    }
};

my leetcode profile given below :

https://leetcode.com/u/vinaykumar333j/

my greek for greek profile given below:

https://www.geeksforgeeks.org/user/vinaykum6ho4/

Post a Comment

0 Comments