博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Add two numbers without using arithmetic operators
阅读量:4150 次
发布时间:2019-05-25

本文共 1033 字,大约阅读时间需要 3 分钟。

reference: 

Problem Definition:

Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc).

Solution:

Sum of two bits can be obtained by performingXOR (^) of the two bits. Carry bit can be obtained by performingAND (&) of two bits.

We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.

Code:

int Add(int x, int y){    // Iterate till there is no carry      while (y != 0)    {        // carry now contains common set bits of x and y        int carry = x & y;           // Sum of bits of x and y where at least one of the bits is not set        x = x ^ y;          // Carry is shifted by one so that adding it to x gives the required sum        y = carry << 1;    }    return x;}

转载地址:http://wrxti.baihongyu.com/

你可能感兴趣的文章
数组中累加和为定值K的最长子数组长度
查看>>
素数对--腾讯2017校招编程
查看>>
JAVA集合--ArrayList实现原理
查看>>
synchronized与Lock
查看>>
数据库索引
查看>>
实现包含min,max,push,pop函数的栈
查看>>
实验2-6 字符型数据的输入输出
查看>>
实验3-5 编程初步
查看>>
实验4-1 逻辑量的编码和关系操作符
查看>>
实验5-2 for循环结构
查看>>
实验5-3 break语句和continue语句
查看>>
实验5-4 循环的嵌套
查看>>
实验5-5 循环的合并
查看>>
实验5-6 do-while循环结构
查看>>
实验5-7 程序调试入门
查看>>
实验5-8 综合练习
查看>>
第2章实验补充C语言中如何计算补码
查看>>
深入入门正则表达式(java) - 命名捕获
查看>>
使用bash解析xml
查看>>
android系统提供的常用命令行工具
查看>>