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