My Simple Java Solution 250 ms


  • 0
    G

    Idea is following

    1. Make sum as long since I was getting arithmetic overflow exception by using int
    2. nitialize sum to the number passed in.
    3. Now we need to find value of digit at unit, tenths, hundreds place and so forth
    4. Terminating condition is as soon as sum value is less than 9
    5. In case number passed is less than 9 it will not enter the loop and we get same number as answer
    6. Any number greater than 9 will enter loop
    7. In loop we add each digit of number and keep adding to interSum till loop is done
    8. as soon as we come out of loop we give this value to outer variable sum
    9. If this value is more than 9 the while loop will continue else it wil exit
    10. On exiting type case this long value to int

    public int addDigits(int num) {

    long sum = num;
    	
    while(sum >9) {
    	long interSum=0;
    	int unitDigit = 0;
    	for(long i=1;i<=sum;i=i*10) {  
    		if(i>sum){
    			break;
    		}
    		long divResult = sum/i;
    		long digit = divResult%10;
    		interSum+=digit;
    		
    	}	
    	sum = interSum;
    }
    return (int)sum;
    

    }


  • 0

    Have you saw the Hint or other's solution? You didn't go deep enough


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.