---
# System prepended metadata

title: Untitled

---

# 作業 3 程式語言十八般武藝

[TOC]

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

# C
```
int getSum(int a, int b) {
    while (b != 0) {
        // AND 運算
        int carry = a & b;
        
        // XOR 運算
        a = a ^ b;
        
        // 將進位值左移一位
        b = (unsigned int)(carry) << 1;
    }
    return a;  // 輸出
}


```
# C++
```
class Solution {
public:
    int getSum(int a, int b) {
        while (b != 0) {
            int carry = a & b;  // 這裡計算進位值
            a = a ^ b;          // 計算非進位值
            b = carry << 1;     // 左移一位
        }
        return a;  // 輸出
    }
};


```

# Java
```
public class Solution {
    public int getSum(int a, int b) {
        while (b != 0) {
            int carry = a & b;  // and
            a = a ^ b;          // xor
            b = carry << 1;     // 左移一位
        }
        return a;  // 輸出
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int a = 1, b = 2;
        System.out.println("Input: a = " + a + ", b = " + b);
        int result = solution.getSum(a, b);
        System.out.println("Output: " + result);
    }
    
    
}
```

# PHP
```
class Solution {

    /**
     * @param Integer $a
     * @param Integer $b
     * @return Integer
     */
    function getSum($a, $b) {
        while ($b != 0) {
            // AND 運算
            $carry = $a & $b;
            
            //  XOR 運算
            $a = $a ^ $b;
            
            // 將進位值左移一位
            $b = $carry << 1;
        }
        return $a;  // 輸出
    }
}

```

# swift

```
class Solution {
    func getSum(_ a: Int, _ b: Int) -> Int {
        var a = a
        var b = b
        
        while b != 0 {
            //  AND 運算
            let carry = a & b
            
            // XOR 運算
            a = a ^ b
            
            // 將進位值左移一位
            b = carry << 1
        }
        
        return a  //輸出
    }
}

```

# TypeScript
```
function getSum(a: number, b: number): number {
    while (b !== 0) {
        //  AND 運算
        const carry = a & b;

        //  XOR 運算
        a = a ^ b;

        // 左移一位
        b = carry << 1;
    }

    return a;  // 輸出
}
```

# Kotlin

```
class Solution {
    fun getSum(a: Int, b: Int): Int {
        var a = a
        var b = b

        while (b != 0) {
            // AND 運算
            val carry = a and b

            // XOR 運算
            a = a xor b

            // 左移一位
            b = carry shl 1
        }

        return a  // 輸出
    }
}
```

