Sharing my C code


  • 1
    M
    int calculate(char* s) {
        int tempsol=0;
        int ifneg=0;
        int tempnums[1000]={0};
        int tempop[1000]={0};
        int temppos=0;
        do{
            if(*s == ' ')
                s++;
            else if(*s == '+'){
                s++;
                ifneg=0;
            }
            else if(*s == '-'){
                s++;
                ifneg=1;
            }
            else if(*s == '('){
                tempnums[temppos] = tempsol;
                if(ifneg)
                    tempop[temppos] = 1;
                else
                    tempop[temppos] = 0;
                temppos++;
                tempsol = 0;
                ifneg = 0;
                s++;
            }
            else if(*s == ')'){
                temppos--;
                if(tempop[temppos])
                    tempsol = tempnums[temppos] - tempsol;
                else
                    tempsol = tempnums[temppos] + tempsol;
                tempnums[temppos] = 0;
                tempop[temppos] = 0;
                ifneg = 0;
                s++;
            }
            else if(*s >= '0' && *s <= '9'){
                char tempstr[100]={0};
                int tmpstrpos=0;
                while(*s != '+' && *s != '-' && *s != ' '&& *s != ')' && *s != '('&& *s != '\0'){
                    tempstr[tmpstrpos++] = *s++;
                }
                int tmpstr_num = (int)atoi(tempstr);
                if(ifneg)
                    tempsol -= tmpstr_num;
                else
                    tempsol += tmpstr_num;
            }
        }while(*s != '\0');
        return tempsol;
    }

Log in to reply
 

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