What is a^b and (a&b)<<1?2019 Community Moderator ElectionWhat is the best way to add two numbers without using the + operator?Adding two numbers without + operator (Clarification)adds two numbers without using + or any arithmetic operatorsAdding two numbers without using the addition operatorWhat is the most efficient way to deep clone an object in JavaScript?What is the preferred syntax for defining enums in JavaScript?What is the scope of variables in JavaScript?What is the !! (not not) operator in JavaScript?What is the JavaScript version of sleep()?What does “use strict” do in JavaScript, and what is the reasoning behind it?What is the 'new' keyword in JavaScript?What is the difference between call and apply?What is JSONP, and why was it created?What is the difference between Bower and npm?

How to use deus ex machina safely?

Look at your watch and tell me what time is it. vs Look at your watch and tell me what time it is

How difficult is it to simply disable/disengage the MCAS on Boeing 737 Max 8 & 9 Aircraft?

Gravity magic - How does it work?

How to make healing in an exploration game interesting

Science-fiction short story where space navy wanted hospital ships and settlers had guns mounted everywhere

PTIJ: Who should I vote for? (21st Knesset Edition)

How could a scammer know the apps on my phone / iTunes account?

Could the Saturn V actually have launched astronauts around Venus?

My Graph Theory Students

What has been your most complicated TikZ drawing?

Is this a real picture of Jordan Peterson in New Zealand with a fan wearing a shirt that says "I'm a Proud Islamaphobe"?

Error in Twin Prime Conjecture

A Cautionary Suggestion

SOQL: Populate a Literal List in WHERE IN Clause

Official degrees of earth’s rotation per day

Is there a data structure that only stores hash codes and not the actual objects?

Are there verbs that are neither telic, or atelic?

Why is the President allowed to veto a cancellation of emergency powers?

Gantt Chart like rectangles with log scale

Most cost effective thermostat setting: consistent temperature vs. lowest temperature possible

What approach do we need to follow for projects without a test environment?

Dice rolling probability game

Can I use USB data pins as power source



What is a^b and (a&b)



2019 Community Moderator ElectionWhat is the best way to add two numbers without using the + operator?Adding two numbers without + operator (Clarification)adds two numbers without using + or any arithmetic operatorsAdding two numbers without using the addition operatorWhat is the most efficient way to deep clone an object in JavaScript?What is the preferred syntax for defining enums in JavaScript?What is the scope of variables in JavaScript?What is the !! (not not) operator in JavaScript?What is the JavaScript version of sleep()?What does “use strict” do in JavaScript, and what is the reasoning behind it?What is the 'new' keyword in JavaScript?What is the difference between call and apply?What is JSONP, and why was it created?What is the difference between Bower and npm?










8















I was doing this question in leetcode.



Request:




Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.




I can't understand the solution it gave



Could someone explain how this getSum function works?



Here is answer's JS:




var getSum=function(a,b)
const Sum=a^b;//I can't understand it.Please give me an example to understand it
const carry=(a&b)<<1;//I can't understand it too
if(!carry)
return Sum

return getSum(Sum,carry);
;
console.log(getSum(5,1));












share|improve this question


























    8















    I was doing this question in leetcode.



    Request:




    Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.




    I can't understand the solution it gave



    Could someone explain how this getSum function works?



    Here is answer's JS:




    var getSum=function(a,b)
    const Sum=a^b;//I can't understand it.Please give me an example to understand it
    const carry=(a&b)<<1;//I can't understand it too
    if(!carry)
    return Sum

    return getSum(Sum,carry);
    ;
    console.log(getSum(5,1));












    share|improve this question
























      8












      8








      8


      1






      I was doing this question in leetcode.



      Request:




      Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.




      I can't understand the solution it gave



      Could someone explain how this getSum function works?



      Here is answer's JS:




      var getSum=function(a,b)
      const Sum=a^b;//I can't understand it.Please give me an example to understand it
      const carry=(a&b)<<1;//I can't understand it too
      if(!carry)
      return Sum

      return getSum(Sum,carry);
      ;
      console.log(getSum(5,1));












      share|improve this question














      I was doing this question in leetcode.



      Request:




      Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.




      I can't understand the solution it gave



      Could someone explain how this getSum function works?



      Here is answer's JS:




      var getSum=function(a,b)
      const Sum=a^b;//I can't understand it.Please give me an example to understand it
      const carry=(a&b)<<1;//I can't understand it too
      if(!carry)
      return Sum

      return getSum(Sum,carry);
      ;
      console.log(getSum(5,1));








      var getSum=function(a,b)
      const Sum=a^b;//I can't understand it.Please give me an example to understand it
      const carry=(a&b)<<1;//I can't understand it too
      if(!carry)
      return Sum

      return getSum(Sum,carry);
      ;
      console.log(getSum(5,1));





      var getSum=function(a,b)
      const Sum=a^b;//I can't understand it.Please give me an example to understand it
      const carry=(a&b)<<1;//I can't understand it too
      if(!carry)
      return Sum

      return getSum(Sum,carry);
      ;
      console.log(getSum(5,1));






      javascript






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 2 hours ago









      JackyJacky

      1758




      1758






















          4 Answers
          4






          active

          oldest

          votes


















          9














          Let's imagine that a = 3 and b = 5



          In binary notation they are a = 0011 and b = 0101



          XOR:
          a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



          So when we're doing a^b result will be 0110 (6 in decimal)



          AND + SHIFT



          a&b performs logical AND operation. It returns 1 only when a = b = 1.



          In our case the result is 0001



          << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



          Next iterations:



          Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



          Now a^b = 0100 and (a&b)<<1 = 0100



          Repeating again.



          Now a^b = 0000 and (a&b)<<1 = 1000



          And again.



          Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



          Everything worked fine since 3+5=8






          share|improve this answer




















          • 1





            Great explanation! I always find the bitwise operations hard to understand

            – Francisco Hanna
            1 hour ago


















          1














           int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
          int carry = (p & q) << 1; // Left Shift, 1+1=2
          if (carry != 0)
          return getSum(result, carry);

          return result;


          Start By p=5,q=6. Then the XOR would be,



          0101
          0110
          ------
          0011


          So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



          0101
          0110
          -------
          0100


          We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



           0100<<1=1000


          So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



          getSum(3, 8);


          So, doing the first XORing we get,



          0011
          1000
          -------
          1011


          The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



          0011
          1000
          -------
          0000


          We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
          As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



          Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.






          share|improve this answer
































            0














            It's basically replicating the half-adder



            Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



            ╔═══════╤═════════════╗
            ║ Input │ Output ║
            ╠═══╤═══╪═══════╤═════╣
            ║ A │ B │ carry │ sum ║
            ╟───┼───┼───────┼─────╢
            ║ 0 │ 0 │ 0 │ 0 ║
            ╟───┼───┼───────┼─────╢
            ║ 1 │ 0 │ 0 │ 1 ║
            ╟───┼───┼───────┼─────╢
            ║ 0 │ 1 │ 0 │ 1 ║
            ╟───┼───┼───────┼─────╢
            ║ 1 │ 1 │ 1 │ 0 ║
            ╚═══╧═══╧═══════╧═════╝


            From the table we get the logic for the outputs: carry = A and B, sum = A xor B





            So the snippet above is working like this



            const Sum=a^b; // sum = a xor b
            const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
            if(!carry)
            return Sum; // no carry, so sum + carry = sum

            return getSum(Sum,carry); // a + b = sum + carry


            See also



            • Adding two numbers without + operator (Clarification)

            • What is the best way to add two numbers without using the + operator?

            • adds two numbers without using + or any arithmetic operators

            • Adding two numbers without using the addition operator





            share|improve this answer






























              -1














              These are bitwise operations. They're close to hardware language.






              share|improve this answer


















              • 7





                Too short.You didn't explain why this works and how

                – Jacky
                2 hours ago






              • 1





                Link-only answers are discouraged here. Please add the relevant content in the answer itself.

                – Ian McLaird
                2 hours ago






              • 3





                It’s binary math. WofWca would have to give you a very very long explanation on binary to explain it. You should really read the W3 Schools article or watch some videos on Bitwise calculations. It’s the kind of thing that would be a few days of class work in college. The comment about link-only answers is fair, but I doubt you’ll grasp the concept from a StackOverflow post alone though.

                – Nate
                2 hours ago







              • 1





                @IanMcLaird It's not a link-only answer. The link content ("bitwise operations") is sufficient as an answer. Similar to an answer such as "Use the method abc.def.xyz".

                – user202729
                1 hour ago






              • 2





                @Jacky You didn't say that you don't know those, did you? If you had known what bitwise operations are, this answers would be sufficient (which may happen in case you are familiar with bitwise operations in another language, and don't know where to find the documentation and is completely unfamiliar with JS)

                – user202729
                1 hour ago










              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55193135%2fwhat-is-ab-and-ab1%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              9














              Let's imagine that a = 3 and b = 5



              In binary notation they are a = 0011 and b = 0101



              XOR:
              a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



              So when we're doing a^b result will be 0110 (6 in decimal)



              AND + SHIFT



              a&b performs logical AND operation. It returns 1 only when a = b = 1.



              In our case the result is 0001



              << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



              Next iterations:



              Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



              Now a^b = 0100 and (a&b)<<1 = 0100



              Repeating again.



              Now a^b = 0000 and (a&b)<<1 = 1000



              And again.



              Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



              Everything worked fine since 3+5=8






              share|improve this answer




















              • 1





                Great explanation! I always find the bitwise operations hard to understand

                – Francisco Hanna
                1 hour ago















              9














              Let's imagine that a = 3 and b = 5



              In binary notation they are a = 0011 and b = 0101



              XOR:
              a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



              So when we're doing a^b result will be 0110 (6 in decimal)



              AND + SHIFT



              a&b performs logical AND operation. It returns 1 only when a = b = 1.



              In our case the result is 0001



              << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



              Next iterations:



              Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



              Now a^b = 0100 and (a&b)<<1 = 0100



              Repeating again.



              Now a^b = 0000 and (a&b)<<1 = 1000



              And again.



              Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



              Everything worked fine since 3+5=8






              share|improve this answer




















              • 1





                Great explanation! I always find the bitwise operations hard to understand

                – Francisco Hanna
                1 hour ago













              9












              9








              9







              Let's imagine that a = 3 and b = 5



              In binary notation they are a = 0011 and b = 0101



              XOR:
              a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



              So when we're doing a^b result will be 0110 (6 in decimal)



              AND + SHIFT



              a&b performs logical AND operation. It returns 1 only when a = b = 1.



              In our case the result is 0001



              << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



              Next iterations:



              Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



              Now a^b = 0100 and (a&b)<<1 = 0100



              Repeating again.



              Now a^b = 0000 and (a&b)<<1 = 1000



              And again.



              Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



              Everything worked fine since 3+5=8






              share|improve this answer















              Let's imagine that a = 3 and b = 5



              In binary notation they are a = 0011 and b = 0101



              XOR:
              a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



              So when we're doing a^b result will be 0110 (6 in decimal)



              AND + SHIFT



              a&b performs logical AND operation. It returns 1 only when a = b = 1.



              In our case the result is 0001



              << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



              Next iterations:



              Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



              Now a^b = 0100 and (a&b)<<1 = 0100



              Repeating again.



              Now a^b = 0000 and (a&b)<<1 = 1000



              And again.



              Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



              Everything worked fine since 3+5=8







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 1 hour ago

























              answered 1 hour ago









              vicodinvicodin

              1,107624




              1,107624







              • 1





                Great explanation! I always find the bitwise operations hard to understand

                – Francisco Hanna
                1 hour ago












              • 1





                Great explanation! I always find the bitwise operations hard to understand

                – Francisco Hanna
                1 hour ago







              1




              1





              Great explanation! I always find the bitwise operations hard to understand

              – Francisco Hanna
              1 hour ago





              Great explanation! I always find the bitwise operations hard to understand

              – Francisco Hanna
              1 hour ago













              1














               int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
              int carry = (p & q) << 1; // Left Shift, 1+1=2
              if (carry != 0)
              return getSum(result, carry);

              return result;


              Start By p=5,q=6. Then the XOR would be,



              0101
              0110
              ------
              0011


              So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



              0101
              0110
              -------
              0100


              We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



               0100<<1=1000


              So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



              getSum(3, 8);


              So, doing the first XORing we get,



              0011
              1000
              -------
              1011


              The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



              0011
              1000
              -------
              0000


              We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
              As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



              Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.






              share|improve this answer





























                1














                 int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
                int carry = (p & q) << 1; // Left Shift, 1+1=2
                if (carry != 0)
                return getSum(result, carry);

                return result;


                Start By p=5,q=6. Then the XOR would be,



                0101
                0110
                ------
                0011


                So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



                0101
                0110
                -------
                0100


                We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



                 0100<<1=1000


                So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



                getSum(3, 8);


                So, doing the first XORing we get,



                0011
                1000
                -------
                1011


                The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



                0011
                1000
                -------
                0000


                We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
                As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



                Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.






                share|improve this answer



























                  1












                  1








                  1







                   int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
                  int carry = (p & q) << 1; // Left Shift, 1+1=2
                  if (carry != 0)
                  return getSum(result, carry);

                  return result;


                  Start By p=5,q=6. Then the XOR would be,



                  0101
                  0110
                  ------
                  0011


                  So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



                  0101
                  0110
                  -------
                  0100


                  We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



                   0100<<1=1000


                  So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



                  getSum(3, 8);


                  So, doing the first XORing we get,



                  0011
                  1000
                  -------
                  1011


                  The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



                  0011
                  1000
                  -------
                  0000


                  We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
                  As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



                  Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.






                  share|improve this answer















                   int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
                  int carry = (p & q) << 1; // Left Shift, 1+1=2
                  if (carry != 0)
                  return getSum(result, carry);

                  return result;


                  Start By p=5,q=6. Then the XOR would be,



                  0101
                  0110
                  ------
                  0011


                  So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



                  0101
                  0110
                  -------
                  0100


                  We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



                   0100<<1=1000


                  So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



                  getSum(3, 8);


                  So, doing the first XORing we get,



                  0011
                  1000
                  -------
                  1011


                  The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



                  0011
                  1000
                  -------
                  0000


                  We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
                  As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



                  Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 1 hour ago

























                  answered 1 hour ago









                  Ayan_84Ayan_84

                  520513




                  520513





















                      0














                      It's basically replicating the half-adder



                      Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



                      ╔═══════╤═════════════╗
                      ║ Input │ Output ║
                      ╠═══╤═══╪═══════╤═════╣
                      ║ A │ B │ carry │ sum ║
                      ╟───┼───┼───────┼─────╢
                      ║ 0 │ 0 │ 0 │ 0 ║
                      ╟───┼───┼───────┼─────╢
                      ║ 1 │ 0 │ 0 │ 1 ║
                      ╟───┼───┼───────┼─────╢
                      ║ 0 │ 1 │ 0 │ 1 ║
                      ╟───┼───┼───────┼─────╢
                      ║ 1 │ 1 │ 1 │ 0 ║
                      ╚═══╧═══╧═══════╧═════╝


                      From the table we get the logic for the outputs: carry = A and B, sum = A xor B





                      So the snippet above is working like this



                      const Sum=a^b; // sum = a xor b
                      const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
                      if(!carry)
                      return Sum; // no carry, so sum + carry = sum

                      return getSum(Sum,carry); // a + b = sum + carry


                      See also



                      • Adding two numbers without + operator (Clarification)

                      • What is the best way to add two numbers without using the + operator?

                      • adds two numbers without using + or any arithmetic operators

                      • Adding two numbers without using the addition operator





                      share|improve this answer



























                        0














                        It's basically replicating the half-adder



                        Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



                        ╔═══════╤═════════════╗
                        ║ Input │ Output ║
                        ╠═══╤═══╪═══════╤═════╣
                        ║ A │ B │ carry │ sum ║
                        ╟───┼───┼───────┼─────╢
                        ║ 0 │ 0 │ 0 │ 0 ║
                        ╟───┼───┼───────┼─────╢
                        ║ 1 │ 0 │ 0 │ 1 ║
                        ╟───┼───┼───────┼─────╢
                        ║ 0 │ 1 │ 0 │ 1 ║
                        ╟───┼───┼───────┼─────╢
                        ║ 1 │ 1 │ 1 │ 0 ║
                        ╚═══╧═══╧═══════╧═════╝


                        From the table we get the logic for the outputs: carry = A and B, sum = A xor B





                        So the snippet above is working like this



                        const Sum=a^b; // sum = a xor b
                        const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
                        if(!carry)
                        return Sum; // no carry, so sum + carry = sum

                        return getSum(Sum,carry); // a + b = sum + carry


                        See also



                        • Adding two numbers without + operator (Clarification)

                        • What is the best way to add two numbers without using the + operator?

                        • adds two numbers without using + or any arithmetic operators

                        • Adding two numbers without using the addition operator





                        share|improve this answer

























                          0












                          0








                          0







                          It's basically replicating the half-adder



                          Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



                          ╔═══════╤═════════════╗
                          ║ Input │ Output ║
                          ╠═══╤═══╪═══════╤═════╣
                          ║ A │ B │ carry │ sum ║
                          ╟───┼───┼───────┼─────╢
                          ║ 0 │ 0 │ 0 │ 0 ║
                          ╟───┼───┼───────┼─────╢
                          ║ 1 │ 0 │ 0 │ 1 ║
                          ╟───┼───┼───────┼─────╢
                          ║ 0 │ 1 │ 0 │ 1 ║
                          ╟───┼───┼───────┼─────╢
                          ║ 1 │ 1 │ 1 │ 0 ║
                          ╚═══╧═══╧═══════╧═════╝


                          From the table we get the logic for the outputs: carry = A and B, sum = A xor B





                          So the snippet above is working like this



                          const Sum=a^b; // sum = a xor b
                          const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
                          if(!carry)
                          return Sum; // no carry, so sum + carry = sum

                          return getSum(Sum,carry); // a + b = sum + carry


                          See also



                          • Adding two numbers without + operator (Clarification)

                          • What is the best way to add two numbers without using the + operator?

                          • adds two numbers without using + or any arithmetic operators

                          • Adding two numbers without using the addition operator





                          share|improve this answer













                          It's basically replicating the half-adder



                          Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



                          ╔═══════╤═════════════╗
                          ║ Input │ Output ║
                          ╠═══╤═══╪═══════╤═════╣
                          ║ A │ B │ carry │ sum ║
                          ╟───┼───┼───────┼─────╢
                          ║ 0 │ 0 │ 0 │ 0 ║
                          ╟───┼───┼───────┼─────╢
                          ║ 1 │ 0 │ 0 │ 1 ║
                          ╟───┼───┼───────┼─────╢
                          ║ 0 │ 1 │ 0 │ 1 ║
                          ╟───┼───┼───────┼─────╢
                          ║ 1 │ 1 │ 1 │ 0 ║
                          ╚═══╧═══╧═══════╧═════╝


                          From the table we get the logic for the outputs: carry = A and B, sum = A xor B





                          So the snippet above is working like this



                          const Sum=a^b; // sum = a xor b
                          const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
                          if(!carry)
                          return Sum; // no carry, so sum + carry = sum

                          return getSum(Sum,carry); // a + b = sum + carry


                          See also



                          • Adding two numbers without + operator (Clarification)

                          • What is the best way to add two numbers without using the + operator?

                          • adds two numbers without using + or any arithmetic operators

                          • Adding two numbers without using the addition operator






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 27 mins ago









                          phuclvphuclv

                          15.2k853228




                          15.2k853228





















                              -1














                              These are bitwise operations. They're close to hardware language.






                              share|improve this answer


















                              • 7





                                Too short.You didn't explain why this works and how

                                – Jacky
                                2 hours ago






                              • 1





                                Link-only answers are discouraged here. Please add the relevant content in the answer itself.

                                – Ian McLaird
                                2 hours ago






                              • 3





                                It’s binary math. WofWca would have to give you a very very long explanation on binary to explain it. You should really read the W3 Schools article or watch some videos on Bitwise calculations. It’s the kind of thing that would be a few days of class work in college. The comment about link-only answers is fair, but I doubt you’ll grasp the concept from a StackOverflow post alone though.

                                – Nate
                                2 hours ago







                              • 1





                                @IanMcLaird It's not a link-only answer. The link content ("bitwise operations") is sufficient as an answer. Similar to an answer such as "Use the method abc.def.xyz".

                                – user202729
                                1 hour ago






                              • 2





                                @Jacky You didn't say that you don't know those, did you? If you had known what bitwise operations are, this answers would be sufficient (which may happen in case you are familiar with bitwise operations in another language, and don't know where to find the documentation and is completely unfamiliar with JS)

                                – user202729
                                1 hour ago















                              -1














                              These are bitwise operations. They're close to hardware language.






                              share|improve this answer


















                              • 7





                                Too short.You didn't explain why this works and how

                                – Jacky
                                2 hours ago






                              • 1





                                Link-only answers are discouraged here. Please add the relevant content in the answer itself.

                                – Ian McLaird
                                2 hours ago






                              • 3





                                It’s binary math. WofWca would have to give you a very very long explanation on binary to explain it. You should really read the W3 Schools article or watch some videos on Bitwise calculations. It’s the kind of thing that would be a few days of class work in college. The comment about link-only answers is fair, but I doubt you’ll grasp the concept from a StackOverflow post alone though.

                                – Nate
                                2 hours ago







                              • 1





                                @IanMcLaird It's not a link-only answer. The link content ("bitwise operations") is sufficient as an answer. Similar to an answer such as "Use the method abc.def.xyz".

                                – user202729
                                1 hour ago






                              • 2





                                @Jacky You didn't say that you don't know those, did you? If you had known what bitwise operations are, this answers would be sufficient (which may happen in case you are familiar with bitwise operations in another language, and don't know where to find the documentation and is completely unfamiliar with JS)

                                – user202729
                                1 hour ago













                              -1












                              -1








                              -1







                              These are bitwise operations. They're close to hardware language.






                              share|improve this answer













                              These are bitwise operations. They're close to hardware language.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 2 hours ago









                              WofWcaWofWca

                              40819




                              40819







                              • 7





                                Too short.You didn't explain why this works and how

                                – Jacky
                                2 hours ago






                              • 1





                                Link-only answers are discouraged here. Please add the relevant content in the answer itself.

                                – Ian McLaird
                                2 hours ago






                              • 3





                                It’s binary math. WofWca would have to give you a very very long explanation on binary to explain it. You should really read the W3 Schools article or watch some videos on Bitwise calculations. It’s the kind of thing that would be a few days of class work in college. The comment about link-only answers is fair, but I doubt you’ll grasp the concept from a StackOverflow post alone though.

                                – Nate
                                2 hours ago







                              • 1





                                @IanMcLaird It's not a link-only answer. The link content ("bitwise operations") is sufficient as an answer. Similar to an answer such as "Use the method abc.def.xyz".

                                – user202729
                                1 hour ago






                              • 2





                                @Jacky You didn't say that you don't know those, did you? If you had known what bitwise operations are, this answers would be sufficient (which may happen in case you are familiar with bitwise operations in another language, and don't know where to find the documentation and is completely unfamiliar with JS)

                                – user202729
                                1 hour ago












                              • 7





                                Too short.You didn't explain why this works and how

                                – Jacky
                                2 hours ago






                              • 1





                                Link-only answers are discouraged here. Please add the relevant content in the answer itself.

                                – Ian McLaird
                                2 hours ago






                              • 3





                                It’s binary math. WofWca would have to give you a very very long explanation on binary to explain it. You should really read the W3 Schools article or watch some videos on Bitwise calculations. It’s the kind of thing that would be a few days of class work in college. The comment about link-only answers is fair, but I doubt you’ll grasp the concept from a StackOverflow post alone though.

                                – Nate
                                2 hours ago







                              • 1





                                @IanMcLaird It's not a link-only answer. The link content ("bitwise operations") is sufficient as an answer. Similar to an answer such as "Use the method abc.def.xyz".

                                – user202729
                                1 hour ago






                              • 2





                                @Jacky You didn't say that you don't know those, did you? If you had known what bitwise operations are, this answers would be sufficient (which may happen in case you are familiar with bitwise operations in another language, and don't know where to find the documentation and is completely unfamiliar with JS)

                                – user202729
                                1 hour ago







                              7




                              7





                              Too short.You didn't explain why this works and how

                              – Jacky
                              2 hours ago





                              Too short.You didn't explain why this works and how

                              – Jacky
                              2 hours ago




                              1




                              1





                              Link-only answers are discouraged here. Please add the relevant content in the answer itself.

                              – Ian McLaird
                              2 hours ago





                              Link-only answers are discouraged here. Please add the relevant content in the answer itself.

                              – Ian McLaird
                              2 hours ago




                              3




                              3





                              It’s binary math. WofWca would have to give you a very very long explanation on binary to explain it. You should really read the W3 Schools article or watch some videos on Bitwise calculations. It’s the kind of thing that would be a few days of class work in college. The comment about link-only answers is fair, but I doubt you’ll grasp the concept from a StackOverflow post alone though.

                              – Nate
                              2 hours ago






                              It’s binary math. WofWca would have to give you a very very long explanation on binary to explain it. You should really read the W3 Schools article or watch some videos on Bitwise calculations. It’s the kind of thing that would be a few days of class work in college. The comment about link-only answers is fair, but I doubt you’ll grasp the concept from a StackOverflow post alone though.

                              – Nate
                              2 hours ago





                              1




                              1





                              @IanMcLaird It's not a link-only answer. The link content ("bitwise operations") is sufficient as an answer. Similar to an answer such as "Use the method abc.def.xyz".

                              – user202729
                              1 hour ago





                              @IanMcLaird It's not a link-only answer. The link content ("bitwise operations") is sufficient as an answer. Similar to an answer such as "Use the method abc.def.xyz".

                              – user202729
                              1 hour ago




                              2




                              2





                              @Jacky You didn't say that you don't know those, did you? If you had known what bitwise operations are, this answers would be sufficient (which may happen in case you are familiar with bitwise operations in another language, and don't know where to find the documentation and is completely unfamiliar with JS)

                              – user202729
                              1 hour ago





                              @Jacky You didn't say that you don't know those, did you? If you had known what bitwise operations are, this answers would be sufficient (which may happen in case you are familiar with bitwise operations in another language, and don't know where to find the documentation and is completely unfamiliar with JS)

                              – user202729
                              1 hour ago

















                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55193135%2fwhat-is-ab-and-ab1%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

                              Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

                              Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar