Sum of Two integers
两个整数相加不能用加减
用位运算
假设两整数a=2和b=6,它们的二进制表示分别为010和110
sum=a^b表示两个二进制数相加不考虑进位:
010
^ 110
= 100
carry=(a&b)<<1表示两个二进数相加的进位
010
& 110
= 010
<<1
=100
递归地做sum^carry直到carry=0
代码(一行反而比较好理解):
int getSum(int a, int b) {
return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
}
Sum of Two integers的更多相关文章
- [LeetCode] Sum of Two Integers 两数之和
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...
- LeetCode Sum of Two Integers
原题链接在这里:https://leetcode.com/problems/sum-of-two-integers/ 题目: Calculate the sum of two integers a a ...
- Nim Game,Reverse String,Sum of Two Integers
下面是今天写的几道题: 292. Nim Game You are playing the following Nim Game with your friend: There is a heap o ...
- LeetCode 371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...
- leetcode371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...
- 【LeetCode】Sum of Two Integers
问题描述: Calculate the sum of two integers a and b, but you are not allowed to use the operator + and - ...
- 每天一道LeetCode--371. Sum of Two Integers
alculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Examp ...
- 371. Sum of Two Integers -- Avota
问题描述: Calculate the sum of two integers a and b, but you are not allowed to use the operator + and - ...
- Leetcode 371: Sum of Two Integers(使用位运算实现)
题目是:Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. ...
- LeetCode 371. Sum of Two Integers (两数之和)
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...
随机推荐
- 团队开发——冲刺1.b
冲刺阶段一(第二天) 1.昨天做了什么? 在了解C#的基础上,深入熟悉Windows窗体应用程序,熟练掌握基本功能 2.今天准备做什么? 在C#的Windows窗体应用程序中,设计简单的游戏开始主界面 ...
- javascript笔记8-表单脚本、JSON、AJAX
通过表单提交,很方便的可以从界面把参数传递给后台. 如果前后台我们有大量数据需要交互,JSON方便我们传递和读取. 如果需要更新一个界面的某一部分数据,并不想刷新界面,就要用到Ajax. 1. 表单脚 ...
- LayaAir引擎——(一)
LayaAir是LayaBox推出的Html5游戏引擎,支持 ActionScript3.TypeScript.JavaScript,开源,并且商用免费. LayaAir IDE 是一款使用Lay ...
- Lua协程
协作例程 1.同一时刻仅一个例程在运行 2.执行权让渡和恢复[栈]
- Oracle 查看表空间的大小及使用情况sql语句
--1.查看表空间的名称及大小 )), ) ts_size FROM dba_tablespaces t, dba_data_files d WHERE t.tablespace_name = d.t ...
- iar 错误解决
使用原来备份的项目可以正确烧写并进入调试状态,但使用新项目则报错,错误提示为Failed to load debugee: E:\工作\项目-农业\KaCES-F\Debug\Exe\kaces.tx ...
- YMMI001-采购单审批
************************************************************************ Report : YMMI1 ** Applicati ...
- C 内存管理初步了解
1 首先变量了解几个概念 静态变量:用 static 修饰的变量 局部变量: 存储在栈区:作用域是函数块内:生存期是直到函数块结束 全局变量:存储在静态区:作用域是从定义到本源程序结束,生存期是运行期 ...
- CE5 中断
一.intr.h里面定义硬件中断号 #define IRQ_EINT0 0 #define IRQ_EINT1 1 #define IRQ_EINT2 2 #define IRQ_EINT3 3 #d ...
- HDU 2577(DP)
题意:要求一个字符串输入,按键盘的最少次数.有Caps Lock和Shift两种转换大小写输入的方式 思路:用dpa与dpb数组分别记录Caps Lock的开关状态,dpa表示不开,dpb表示开 代码 ...