Horje
Add Two Numbers Without using Arithmetic Operators in PHP

This article will show you how to add two numbers without using Arithmetic operators in PHP. There are two methods to add two numbers, these are:

Using Bitwise Operators

We will use Bitwise Operator to add two numbers. First, we check num2 is not equal to zero, then Calculate the carry using & operator, and then use XOR operator to get sum of numbers, At last, shift the carry to 1 left.

PHP

<?php
  
function addNum($num1, $num2) {
    while ($num2 != 0) {
      
        // Calculate the carry
        $carry = $num1 & $num2;
  
        // XOR to get the sum
        $num1 = $num1 ^ $num2;
  
        // Shift the carry to the left
        $num2 = $carry << 1;
    }
  
    return $num1;
}
  
// Driver Code
$num1 = 5;
$num2 = 7;
  
echo "Sum : " . addNum($num1, $num2);
  
?>

Output

Sum : 12

Using Recursion

In this section, we will use the above approach with Recursion to calculate the sum of two numbers.

Example:

PHP

<?php
  
function addNum($num1, $num2) {
    if ($num2 == 0) {
        return $num1;
    } else {
        return addNum($num1 ^ $num2, ($num1 & $num2) << 1);
    }
}
  
// Driver Code
$num1 = 5;
$num2 = 7;
  
echo "Sum : " . addNum($num1, $num2);
  
?>

Output

Sum : 12



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Find First and Last Digits of a Number in PHP Find First and Last Digits of a Number in PHP
Postman vs Making HTTP Request and Asserting Response Postman vs Making HTTP Request and Asserting Response
Seventeenth Amendment Act, 1964 of Indian Constitution Seventeenth Amendment Act, 1964 of Indian Constitution
Importance of Software Testing in the Automotive Industry Importance of Software Testing in the Automotive Industry
Jira Agile Jira Agile

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
8