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
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...