2016-10-14 1 views
0

wurde ich diese Frage in einem Interview gefragt:Wie fügt man zwei Variablen ohne einen '+' Operator ein?

Wie zwei Variablen hinzufügen, ohne einen ‚+‘ Operator?

Der Interviewer fragte mich und ich konnte nicht antworten, obwohl ich ein guter C-Programmierer bin!

+6

Vielleicht 'x - (- y)'? – coredump

+0

Voting zum Schließen einer C-Frage als Duplikat einer C# -Frage ist nicht korrekt. – 2501

+1

@coredump tat das gleiche, aber er bestand darauf, dass ich das nicht tat !! – Anjaneyulu

Antwort

2

Mit bitweise Operatoren können Sie zwei Zahlen hinzufügen. Versuchen Sie unter:

int Sum(int a, int b) 
    { 
     // Iterate till there is no carry 
     while (b != 0) 
     { 
      // now carry contains common set bits of a and b 
      int carry = a & b; 

      // Sum of bits of a and b where at least one of the bits is not set 
      a = a^b; 

      // Carry is shifted by one so that adding it to a gives the required sum 
      b = carry << 1; 
     } 
     return a; 
    } 

Mit erhöhen bzw. verringern Operatoren Sie zwei Zahlen addieren. Der andere Weg könnte wie sein:

int Sum(int a, int b) 
{ 
    // Iterate till there b becomes zero 
    while (b--) 
    { 
     a++; 
    } 
    return a; 
} 
+0

Danke @stubborn – Anjaneyulu

Verwandte Themen