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 ...
随机推荐
- Windows Server 2003 Sp2 下无法安装SQL Server 2008 Management Studio Express问题
Windows Server 2003 Sp2 下无法安装SQL Server 2008 Management Studio Express问题钉子 发表于 2010-5-22 1:42:51问题描述 ...
- jQuery遍历Json数组
var jsonArray= [{ "name": "张三", "password": "123456"},{ &qu ...
- android中图片的三级缓存cache策略(内存/文件/网络)
实现图片缓存也不难,需要有相应的cache策略.这里我采用 内存-文件-网络 三层cache机制,其中内存缓存包括强引用缓存和软引用缓存(SoftReference),其实网络不算cache,这里姑且 ...
- CSS3特性 盒模型 动画
转发自0101后花园 CSS3中的动画功能分为Transitions和Animations功能,这两种功能都可以通过改变CSS中的属性值来产生动画效果. 一.Transitions 语法:transi ...
- BZOJ 2763 分层图最短路
突然发现我不会分层图最短路,写一发. 就是同层中用双向边相连,用单向边连下一层 #include <cstdio> #include <algorithm> #include ...
- 来自HeroKu的HTTP API 设计指南(中文版)
原文转自:http://get.jobdeer.com/343.get 来自HeroKu的HTTP API 设计指南(中文版) 翻译 by @Easy 简介 本指南中文翻译者为 @Easy ,他是国内 ...
- Spring使用——环境部署和配置问题总结
众所周知,spring是Java中一个非常非常重要的框架,主要提供了依赖注入DI,和切面编程AOP.我多年前做过一段时间的Java,不过那时候项目中没有用Spring,所以一直也没有特别注意,最近看了 ...
- UVA 11235 频繁出现的数值 RMQ
题目链接: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem ...
- 评价photoshop
Adobe Photoshop,简称“PS”,是一个由Adobe开发和发行的图像处理软件. 2003年,Adobe的Creative Suite套装将Adobe Photoshop 8更名为Adobe ...
- bk.
http://ol.tgbus.com/zt2013/gzsnew/ 巴士盘点 十大游戏工作室 http://bbs.3dmgame.com/forum.php?mod=viewthread& ...