日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode 371. Sum of Two Integers | 371. 两整数之和(补码运算)

發布時間:2024/2/28 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 371. Sum of Two Integers | 371. 两整数之和(补码运算) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

https://leetcode.com/problems/sum-of-two-integers/

題解

根據 related topics 可知,本題考察二進制運算。

第一次提交的時候,沒想到輸入包含負數,于是又調了好久。

既然題目是二進制運算,就借此機會復習一下補碼吧。

需要知道:

  • 正數的補碼 = 其本身
  • 負數的補碼 = 源碼取反 + 1

補碼的運算如下,參考:補碼加減法運算


class Solution {public int getSum(int a, int b) {int[] binA = toBinary(a);int[] binB = toBinary(b);int[] binSum = addBinary(binA, binB);int res = binToDec(binSum);return res;}// 二進制取反public void negateBinary(int[] arr) {for (int i = 0; i < 32; i++) {arr[i] = 1 - arr[i];}}// 二進制(補碼)->十進制public int binToDec(int[] arr) {boolean minus = false;if (arr[31] == 1) { // 若補碼符號位為1minus = true;negateBinary(arr); // 取反arr = addBinary(arr, toBinary(1)); // 加1}int sum = 0;for (int i = 0; i < 32; i++) {sum += arr[i] * Math.pow(2, i);}if (minus) sum *= -1;return sum;}// 二進制加法public int[] addBinary(int[] a, int[] b) {int carry = 0;int[] sum = new int[32];for (int i = 0; i < 32; i++) {int t = a[i] + b[i] + carry;carry = t >= 2 ? 1 : 0;sum[i] = t % 2;}return sum;}// 十進制->二進制(補碼)public int[] toBinary(int n) {int abs = Math.abs(n);int[] arr = new int[32];int size = 0;while (abs != 0) {arr[size++] = abs % 2;abs /= 2;}if (n < 0) {negateBinary(arr);arr = addBinary(arr, toBinary(1));}return arr;} }

后來看了評論區,才知道這題真正的考察點,以及一些其他的位運算技巧,可以參考:
A summary: how to use bit manipulation to solve problems easily and efficiently

總結

以上是生活随笔為你收集整理的leetcode 371. Sum of Two Integers | 371. 两整数之和(补码运算)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。