About Add Digits


  • 0
    A

    Leetcode told me when the input is "13",the result will be Runtime Error,but I copy this code to VC6.0,it is right and I can get the right answer "4",I cannot understand why,please help..Thanks~

    int result = 0; 
    
    int addDigits(int num) {
        
        char str[11] = {0};
        int len=0;
        int i = 0;
        
        if(num<10){
            return num;
        }
        
        sprintf(str,"%d",num);
        len = strlen(str);
        
        for(i = 0;i < (len/2);i++){
            result += (str[i]-48)+(str[len-1-i]-48);
        }
        if((len%2)!=0){
            result += (str[(len-1)/2]-48);    
        }
        if(result >= 10)
        {
            addDigits(result);
        }
        return result;
    }

Log in to reply
 

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