当前位置:网站首页>LeetCode刷题——两整数之和#371#Medium
LeetCode刷题——两整数之和#371#Medium
2022-07-02 12:04:00 【喷火龙与水箭龟】
两整数之和的思路探讨与源码
两整数之和的题目如下图,该题属于数学类和位运算类型的题目,主要考察对于位运算方法的使用和题目数学思路的理解。本文的题目作者想到2种方法,分别是位运算方法和数学处理方法,其中位运算方法使用Java进行编写,而调用内置函数方法使用Python进行编写,当然这可能不是最优的解法,还希望各位大佬给出更快的算法。
本人认为该题目可以位运算方法的思路进行解决,首先判断参数b是否为0,如果不为0则开始循环,将参数a和参数b进行与运算,然后将运算结果左移1位,将参数a和参数b进行与运算后赋值给参数a,将之前左移后的结果赋值给参数b,以此循环,直到最终跳出循环条件并返回参数a即可。那么按照这个思路我们的Java代码如下:
#喷火龙与水箭龟
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int num = (a & b) << 1;
a = a ^ b;
b = num;
}
return a;
}
}

显然,我们位运算方法的效果还不错,同时还可以使用调用内置函数的方法解决,即直接将参数a和参数b调用系统的内置函数sum()来进行求和,直接得到结果并返回。所以按照这个思路就可以解决,下面是Python代码:
#喷火龙与水箭龟
class Solution:
def getSum(self, a: int, b: int) -> int:
res = sum((a,b))
return res

从结果来说Java版本位运算方法的效率不错,而Python版本的调用内置函数方法的速度也还可以,但应该是有更多的方法可以进一步提速的,希望朋友们能够多多指教,非常感谢。
边栏推荐
- 哈夫曼树:(1)输入各字符及其权值(2)构造哈夫曼树(3)进行哈夫曼编码(4)查找HC[i],得到各字符的哈夫曼编码
- AtCoder Beginner Contest 254
- 07_哈希
- FPGA - 7系列 FPGA内部结构之Clocking -03- 时钟管理模块(CMT)
- TiDB数据迁移工具概览
- Markdown tutorial
- Btrace- (bytecode) dynamic tracking tool
- 16_Redis_Redis持久化
- Set set you don't know
- [noi Simulation Competition] scraping (dynamic planning)
猜你喜欢

GeoServer offline map service construction and layer Publishing

Guangzhou Emergency Management Bureau issued a high temperature and high humidity chemical safety reminder in July

18_ Redis_ Redis master-slave replication & cluster building

15_ Redis_ Redis. Conf detailed explanation

Tidb data migration tool overview

Set set you don't know

TiDB数据迁移工具概览
![[c voice] explain the advanced pointer and points for attention (2)](/img/fb/515e25899bd9a2905ee63cb041934a.png)
[c voice] explain the advanced pointer and points for attention (2)

Practice of compiling principle course -- implementing an interpreter or compiler of elementary function operation language

Pytorch 保存tensor到.mat文件
随机推荐
Recommended configuration of tidb software and hardware environment
原则、语言、编译、解释
Principles, language, compilation, interpretation
【网络安全】网络资产收集
HUSTPC2022
你不知道的Set集合
Map介绍
14_ Redis_ Optimistic lock
CDN 在游戏领域的应用
Dragonfly low code security tool platform development path
. Solution to the problem of Chinese garbled code when net core reads files
The traversal methods of binary tree mainly include: first order traversal, middle order traversal, second order traversal, and hierarchical traversal. First order, middle order, and second order actu
Map introduction
. Net again! Happy 20th birthday
Tidb data migration tool overview
How to avoid 7 common problems in mobile and network availability testing
FPGA - clock-03-clock management module (CMT) of internal structure of 7 Series FPGA
解决el-radio-group 回显后不能编辑问题
Semantic segmentation learning notes (1)
Table responsive layout tips