Bitwise recursive addition of two integers in C - Tutorialspoint

文章推薦指數: 80 %
投票人數:10人

Bitwise recursive addition of two integers in C ; Step 1 − Find XOR of a and b i.e. a^b and store it in the result variable. ; Step 2 − Check if ... Home CodingGround Jobs Whiteboard Tools Business Teachwithus TrendingCategories DataStructure Networking RDBMS OperatingSystem Java iOS HTML CSS Android Python CProgramming C++ C# MongoDB MySQL Javascript PHP SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho BitwiserecursiveadditionoftwointegersinC CServerSideProgrammingProgramming Inthisproblem,wearegiventwonumbers.OurtaskistocreateaCprogramfortheBitwiserecursiveadditionoftwointegers.ThelogictofindthesumusingtheBitwiseoperationsissimilartowhatweusedtodowhenwewereinpreschool.Forfindingthesum,weusedtoaddeachdigitofthenumberandifacarryisthere,weaddittothenextdigit.Wewilldoasimilarthing,findthesumusingtheXORoperatorandcheckforthecarryusingtheANDoperation.Ifthereisacarrywewilladditbacktothenumberotherwisenot.ThisisthelogicofaHalf-Adder whichyoumighthavelearnedindigitalElectronics.Referhere…Now,Thesumiscalculatedusinga^bi.e.anXORbandweneedtocheckforanextracarrythatneedstobepropagatedifthefirstbitofbothissetorso.Andweneedtoaddanextrasetbittothenumber.So,abitalgorithmwillbeStep1−FindXORofaandbi.e.a^bandstoreitintheresultvariable.Step2−Checkif{(a&b)<<1}==0Step2.1−Ifitisequalto0,thenprinttheresult,itisthefinalresult.Step2.2−Ifitisnotequalto0,thengotostep1,witha={(a&b)<<1}andb=result.ExampleProgramtoillustratetheworkingofthealgorithm− LiveDemo#include intaddNumbers(inta,intb){   intcarry=(a&b)<<1;   intresult=a^b;   if(carry==0)    returnresult;   else    addNumbers(carry,result); } intmain(){   inta=54,b=897;   printf("Thesumof%dand%dusingbitwiseaddingis%d",a,b,addNumbers(a,b));   return0; }OutputThesumof54and897usingbitwiseaddingis951’ sudhirsharma Updatedon05-Aug-202008:00:49 RelatedQuestions&AnswersC++ProgramtoPerformAdditionOperationUsingBitwiseOperators DivideTwoIntegersinC++ RecursiveprogramtoprintformulaforGCDofnintegersinC++ CprogramforAdditionandMultiplicationby2usingBitwiseOperations. Pythonprogramadditionoftwomatrix AdditionoftwonumberswithoutpropagatingCarry? SumofTwoIntegersinPython CProgramtoAddtwoIntegers Additionoftwonumberusing‘-‘operator? RangeAdditioninC++ C++programtooverloadadditionoperatortoaddtwomatrices BitwiseORsofSubarraysinC++ RecursiveImplementationofatoi()inC++ Even-oddturngamewithtwointegersinC++ JavaScriptrecursivelooptosumallintegersfromnestedarray? PreviousPage PrintPage NextPage  Advertisements



請為這篇文章評分?