sum (adding 2 numbers ) without plus operator

后端 未结 9 670
借酒劲吻你
借酒劲吻你 2021-02-05 20:42

Can anyone explain the logic how to add a and b?

#include 

int main()
{
     int a=30000, b=20, sum;
     char *p;
             


        
9条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 21:36

    An alternative to the pointer arithmetic is to use bitops:

    #include 
    #include 
    
    unsigned addtwo(unsigned one, unsigned two);
    
    unsigned addtwo(unsigned one, unsigned two)
    {
    unsigned carry;
    
    for( ;two; two = carry << 1)    { 
            carry = one & two; 
            one ^= two;
            } 
    return one;
    }
    
    int main(int argc, char **argv)
    {
    unsigned one, two, result;
    
    if ( sscanf(argv[1], "%u", &one ) < 1) return 0;
    if ( sscanf(argv[2], "%u", &two ) < 1) return 0;
    
    result = addtwo(one, two);
    
    fprintf(stdout, "One:=%u Two=%u Result=%u\n", one, two, result );
    
    return 0;
    }
    

提交回复
热议问题