Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

บวกจำนวนเต็ม 2 จำนวนโดยไม่ใช้ Arithmetic Operators ใน C/C++


ในบทช่วยสอนนี้ เราจะอภิปรายโปรแกรมเพื่อเข้าใจวิธีบวกจำนวนเต็ม 2 จำนวนโดยไม่ใช้ arithmetic operators ใน C/C++

สำหรับการบวก 2 จำนวนเต็มโดยไม่ใช้ arithmetic operators เราสามารถทำได้ด้วย pointers หรือ bitwise operators

ตัวอย่าง

ใช้ pointers

#include <iostream>
using namespace std;
int sum(int a, int b){
    int *p = &a;
    return (int)&p[b];
}
int main() {
    int add = sum(2,3);
    cout << add << endl;
    return 0;
}

ผลลัพธ์

5

ตัวอย่าง

ใช้ bitwise operators

#include <iostream>
using namespace std;
int sum(int a, int b){
    int s = a ^ b;
    int carry = a & b;
    if (carry == 0)
        return s;
    else
        return sum(s, carry << 1);
}
int main() {
    int add = sum(2,3);
    cout << add << endl;
    return 0;
}

ผลลัพธ์

5