简体   繁体   中英

Trying to understand the Shunting Yard Algorithm

I am trying to do the Shunting-yard algorithm so I started researching about it. While doing so, I found some interesting documentation which I do not really understand:

    // Current token is a number, push 
    // it to stack for numbers. 
    else if(isdigit(tokens[i])){ 
        int val = 0; 

        // There may be more than one 
        // digits in number. 
        while(i < tokens.length() && 
                    isdigit(tokens[i])) 
        { 
            val = (val*10) + (tokens[i]-'0'); 
            i++; 
        } 

        values.push(val); 
    } 

I do not understand why inside the while , the variable val is being multiplied by 10 ( val=(val*10) ). Can someone help me understand why the algorithm has to do this?

Because otherwise you'd just add the digits. Say for instance you want 123 : you get 1 , multiply with 10 to get 10 , add 2 to get 12 , multiply with 10 to get 120 , then add 3 to get 123 .

If you omitted the multiplication by 10 , you'd just get 1 + 2 + 3 == 6 instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM