当前位置:网站首页>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版本的调用内置函数方法的速度也还可以,但应该是有更多的方法可以进一步提速的,希望朋友们能够多多指教,非常感谢。
边栏推荐
- XML配置文件
- Learn the method code of using PHP to realize the conversion of Gregorian calendar and lunar calendar
- LeetCode_ Sliding window_ Medium_ 395. Longest substring with at least k repeated characters
- 17_Redis_Redis发布订阅
- 06_栈和队列转换
- 21_ Redis_ Analysis of redis cache penetration and avalanche
- 学习使用php将时间戳转换为大写日期的方法代码示例
- LeetCode_ String_ Simple_ 412.Fizz Buzz
- 损失函数与正负样本分配:YOLO系列
- Principles, language, compilation, interpretation
猜你喜欢

14_ Redis_ Optimistic lock

CodeCraft-22 and Codeforces Round #795 (Div. 2)D,E

19_ Redis_ Manually configure the host after downtime

Facing the challenge of "lack of core", how can Feiling provide a stable and strong guarantee for customers' production capacity?

06_ Stack and queue conversion

How to find a sense of career direction

编译原理课程实践——实现一个初等函数运算语言的解释器或编译器

02_线性表_顺序表

List集合&UML图

数据分析思维分析方法和业务知识——业务指标
随机推荐
Btrace- (bytecode) dynamic tracking tool
Real estate market trend outlook in 2022
你不知道的Set集合
6.12 企业内部upp平台(Unified Process Platform)的关键一刻
20_Redis_哨兵模式
基于RZ/G2L | OK-G2LD-C开发板存储读写速度与网络实测
JVM architecture, classloader, parental delegation mechanism
2021-2022学年编译原理考试重点[华侨大学]
vChain: Enabling Verifiable Boolean Range Queries over Blockchain Databases(sigmod‘2019)
02_线性表_顺序表
Internet Explorer officially retired
可视化搭建页面工具的前世今生
. Net again! Happy 20th birthday
Set set you don't know
05_队列
04.进入云原生后的企业级应用构建的一些思考
10_ Redis_ geospatial_ command
Solve the problem that El radio group cannot be edited after echo
TiDB数据迁移场景综述
损失函数与正负样本分配:YOLO系列