Sum of Two Integers

来源:http://www.cnblogs.com/sofiaT/archive/2016/09/02/5825768.html
-Advertisement-
Play Games

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example:Given a = 1 and b = 2, return 3. 個人思路:繞開+、-,利用 ...


Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

個人思路:繞開+、-,利用迴圈和 += 與 -= 。

class Solution {
public:
  int getSum(int a, int b) {
    double x = a, y = b;
    double c = fabs(y);
    for (double i = 1; i <= c; i++) {
      if (b > 0) a++;
      if (b < 0) a--;
    }
    return a;
  }
};

錯誤原因:特殊值的計算。a = 2147483647, b = -2147483647。Time Limit Exceeded

自己在電腦上跑結果是對的,然而迴圈次數太多了,浪費時間,比較笨的一種方法,年輕人,還是太傻太天真,還需要學習一個。

其他思路:

1.利用下標偏移自帶加法 by dimle

int getSum(int a, int b) {
    auto c = (char*)(a);
    return (int)((int64_t)(&c[b]));
}

把a變成一個地址為a的指針c,把它看成數組,偏移b後,地址變成a + b,再把地址轉成int。(補充學習:<inttypes.h>)

2.利用位運算 by vdvvdd

class Solution {
public:
    int getSum(int a, int b) {
        int sum = a;
        
        while (b != 0)
        {
            sum = a ^ b;//calculate sum of a and b without thinking the carry 
            b = (a & b) << 1;//calculate the carry
            a = sum;//add sum(without carry) and carry
        }
        
        return sum;
    }
};

解釋:

class Solution {
public:
    int getSum(int a, int b) {
        // Take 1 + 2 for example in 4 bits.
        // Same as 0001 + 0010
        // Binary addition requires going through each bit position and
        // generating a carry in bit, carry out bit and sum bit.
        // For example, in bit position 0 in 0001 + 0010, 
        // carry in: 0, sum bit: carry in + 1 + 0 = 1, carry out: 0
        // For bit position 1,
        // carry in: 0, sum bit: carry in + 0 + 1 = 1, carry out: 0
        // Using a truth table, we can figure out that
        // sum bit = carry in xor bit_a xor bit_b.
        // carry out = (carry in AND bit_a) OR (carry in AND bit_b) OR (bit_a AND bit_b)
        // carry out becomes the carry in for the next bit position.
        int result = 0x0;
        int sum_bit = 0x0;
        int carry_bit = 0x0;
        int bitmask = 0x1;
        int bit_a = 0x0;
        int bit_b = 0x0;
        
        int i = 0;  // Keep track of what bit position im in.
        while (bitmask != 0x0) {
            // Isolate bits in each bit position.
            bit_a = (a & bitmask) >> i;
            bit_b = (b & bitmask) >> i;
            
            // Calculate sum, carry_bit is a carry in now.
            sum_bit = ((carry_bit ^ bit_a) ^ bit_b);
            // Shift sum_bit to correct bit position, OR into result.
            result |= (sum_bit << i);
            // Calculate carry out, carry_bit is now a carry out after calculation.
            carry_bit = ((bit_a & bit_b) | (carry_bit & bit_a)) | (carry_bit & bit_b);
            
            // Shift bitmask over 1 to the left.
            bitmask <<= 1;
            // Increment bit position.
            ++i;
        }
        return result;
    }
};

 

 

3. 另一種位運算 by cjchan0210

class Solution {
public:
int getSum(int a, int b) {
if(a && b) return getSum(a^b, (a&b) << 1);
else return a|b;
}
};

viewed as binary, c = (a&b)<<1 means carry bits, and d = a^b means sum without carry obviously...
and then get the sum of c and d...
if a or b is 0, return a or b, so that is a|b

 

 

拓展閱讀:https://discuss.leetcode.com/topic/50315/a-summary-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 轉載請標明出處; 最近在看redis的代碼,發現了有關函數指針的部分,想把它記下來。 在redis中有類似下麵的定義,利用typedef 定義了一個新的類型,這種類型是一個函數: 然後可以用這個類型定義一個指針,這個指針指向一個函數,具體redis中使用如下(具體redis的源碼解析,後面的文章中還 ...
  • 問題就是對一個list中的新聞id進行去重,去重之後要保證順序不變。 直觀方法 最簡單的思路就是: 複製代碼代碼如下: ids = [1,2,3,3,4,2,3,4,5,6,1]news_ids = []for id in ids: if id not in news_ids: news_ids.a ...
  • PHP(personal homepage)是HTML內嵌式語言,是一種在伺服器端執行的嵌入HTML文檔的腳本語言。由zend公司維護。為什麼要安裝web伺服器?因為我們瀏覽器要取數據,從web伺服器湖獲取。httpwatch工具可以獲取發送和接受的數據,有利於我們瞭解的更透徹。伺服器除Appche ...
  • 數據校驗指對數據合法性進行檢查,根據驗證數據的位置可以分為客戶端驗證和伺服器端驗證,今天隨筆主要寫的是實現伺服器端的數據驗證,伺服器端數據驗證主要特點: ·數據提交後在伺服器端驗證 ·防止繞過客戶端驗證提交的非法數據 ·可以在伺服器端處理數據前保證數據的合法性 Struts2中有兩種實現伺服器端驗證 ...
  • ...
  • 三觀是什麼鬼 當我們在討論「三觀一致」的時候是在討論些什麼? 我認為這個世界上本沒有「三觀」這一說法,說的人多了,也就有了「三觀」這個詞,當我們討論「三觀一致」其實並不是真的在說世界觀、價值觀、人生觀,而是再說,你們能不能玩到一起,吃到一起,睡到一起。就這麼簡單 官網下載 因為本文是基於 Windo ...
  • 1)Description: 1)Description: N! (N的階乘) 是非常大的數,計算公式為:N! = N * (N - 1) * (N - 2) * ... * 2 * 1)。現在需要知道N!有多少(十進位)位。 input:每行輸入1個正整數N。0 < N < 1000000 out ...
  • 1)名稱:memset()函數 2)別稱:char型初始化函數 3)功能: 將s所指向的某一塊記憶體中的每個位元組的內容全部設置為ch指定的ASCII值,塊的大小由第三個參數指定,這個函數通常為新申請的記憶體做初始化工作 4)用法: void *memset(void *s, char ch, unsig ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...