当前位置:网站首页>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版本的调用内置函数方法的速度也还可以,但应该是有更多的方法可以进一步提速的,希望朋友们能够多多指教,非常感谢。
边栏推荐
- Tidb hybrid deployment topology
- 18_ Redis_ Redis master-slave replication & cluster building
- 让您的HMI更具优势,FET-G2LD-C核心板是个好选择
- GeoServer offline map service construction and layer Publishing
- 06_ Stack and queue conversion
- 20_ Redis_ Sentinel mode
- Solution of Queen n problem
- Application of CDN in game field
- 06_栈和队列转换
- List set & UML diagram
猜你喜欢
YOLOV5 代码复现以及搭载服务器运行
6.12 企业内部upp平台(Unified Process Platform)的关键一刻
Guangzhou Emergency Management Bureau issued a high temperature and high humidity chemical safety reminder in July
21_Redis_浅析Redis缓存穿透和雪崩
How to find a sense of career direction
Base64 coding can be understood this way
There are 7 seats with great variety, Wuling Jiachen has outstanding product power, large humanized space, and the key price is really fragrant
[noi simulation] Elis (greedy, simulation)
[noi Simulation Competition] scraping (dynamic planning)
Btrace- (bytecode) dynamic tracking tool
随机推荐
MySQL -- Index Optimization -- order by
Topology architecture of the minimum deployment of tidb cluster
04_ Stack
17_Redis_Redis发布订阅
07_ Hash
How to choose a third-party software testing organization for automated acceptance testing of mobile applications
C语言实现N皇后问题
Infra11199 database system
08_ 串
Tidb data migration scenario overview
HUSTPC2022
20_Redis_哨兵模式
13_Redis_事务
Kibana basic operation
How to solve the problem of database content output
Let your HMI have more advantages. Fet-g2ld-c core board is a good choice
How to write sensor data into computer database
AtCoder Beginner Contest 254
Map introduction
百变大7座,五菱佳辰产品力出众,人性化大空间,关键价格真香