371. Sum of Two Integers

2021. 10. 26. 01:56Leetcode

Description:

Given two integers a and b, return the sum of the two integers without using the operators + and -.

 

/*
[1] full-adder)

idea::
using full-adder approach. bit-manipulation

code::
(below)

-T/C: O(32) =O(1). # regardless a and b, iterate 32times
-S/C: O(1)

[2] int to string)

idea::
int -> string -> add -> return

*/
    

class Solution {
    public int getSum(int a, int b) {
        int output=0;
        
        int carry=0;
        for(int i=0;i<32;++i){
            int a_prime=(a>>i)&1;
            int b_prime=(b>>i)&1;
            
            int sum=a_prime^b_prime^carry;
            carry=a_prime&b_prime | b_prime&carry | a_prime&carry;
            
            output=(sum<<i)|output;
        }
            
        return output;
    }
}

'Leetcode' 카테고리의 다른 글

278. First Bad Version  (0) 2021.10.26
226. Invert Binary Tree  (0) 2021.10.26
33. Search in Rotated Sorted Array  (0) 2021.10.26
199. Binary Tree Right Side View  (0) 2021.10.25
103. Binary Tree Zigzag Level Order Traversal  (0) 2021.10.25