【leetcode】306. 累加数

 

bool isAdditiveNumber(char * num){
    int i, j, k, len=strlen(num), pst1=0, pst2=0, bit=0, third;
    char* tmp1=(char*)calloc(22,sizeof(char));
    char* tmp2=(char*)calloc(22,sizeof(char));
    char* tmp3=(char*)calloc(22,sizeof(char));
    for (i=1; i<=len/2; i++){
        if(i>1 && num[0]=='0')
                break;        
        for (j=i+1; j<len && j-i<=len/2; j++){
            memset(tmp1,0x30,21);
            memcpy(tmp1+21-i,num,i*sizeof(char));
            if(j-i>1 && num[i]=='0')
                break;
            memset(tmp2,0x30,21);
            memcpy(tmp2+21-(j-i),num+i,(j-i)*sizeof(char));
            third=j;
            pst2=( 21-(j-i) < 21-i )?21-(j-i) :21-i;
            while(third<len){
                memset(tmp3,0x30,21);
                for (k=20; k>=pst2-1; k--){                
                    tmp3[k] += (tmp1[k]-'0'+tmp2[k]-'0'+bit)%10;
                    bit=(tmp1[k]-'0'+tmp2[k]-'0' +bit >= 10)?1 :0;
                }
                while(k<20 && tmp3[k]=='0')
                    k++;
                if(strncmp(tmp3+k,num+third,20-k+1) == 0){                
                    char* p=tmp1;
                    tmp1=tmp2;
                    tmp2=tmp3;
                    tmp3=p;                    
                    third+=20-k+1;
                    pst2=k;
                }
                else
                    break;
            }
            if(third==len)
                return true;            
        }
    }
    return false;
}

 

posted @ 2021-01-01 22:21  温暖了寂寞  阅读(88)  评论(0编辑  收藏  举报