Add two numbers using ++ and/or —
Last Updated :
22 Jun, 2022
Given two numbers, return a sum of them without using operators + and/or -, and using ++ and/or –.
Examples:
Input: x = 10, y = 5
Output: 15
Input: x = 10, y = -5
Output: 10
We strongly recommend you to minimize your browser and try this yourself first
The idea is to do y times x++, if y is positive, and do y times x– if y is negative.
C++
#include <bits/stdc++.h>
using namespace std;
int add( int x, int y)
{
while (y > 0 && y--)
x++;
while (y < 0 && y++)
x--;
return x;
}
int main()
{
cout << add(43, 23) << endl;
cout << add(43, -23) << endl;
return 0;
}
|
Java
public class GFG {
static int add( int x, int y)
{
while (y > 0 && y != 0 ) {
x++;
y--;
}
while (y < 0 && y != 0 ) {
x--;
y++;
}
return x;
}
public static void main(String args[])
{
System.out.println(add( 43 , 23 ));
System.out.println(add( 43 , - 23 ));
}
}
|
Python3
while (y > 0 and y):
x = x + 1
y = y - 1
while (y < 0 and y) :
x = x - 1
y = y + 1
return x
print (add( 43 , 23 ))
print (add( 43 , - 23 ))
|
C#
using System;
public class GFG {
static int add( int x, int y)
{
while (y > 0 && y != 0) {
x++;
y--;
}
while (y < 0 && y != 0) {
x--;
y++;
}
return x;
}
public static void Main()
{
Console.WriteLine(add(43, 23));
Console.WriteLine(add(43, -23));
}
}
|
PHP
<?php
function add( $x , $y )
{
while ( $y > 0 && $y --)
$x ++;
while ( $y < 0 && $y ++)
$x --;
return $x ;
}
echo add(43, 23), "\n" ;
echo add(43, -23), "\n" ;
?>
|
Javascript
<script>
function add(x, y)
{
while (y > 0 && y != 0) {
x++;
y--;
}
while (y < 0 && y != 0) {
x--;
y++;
}
return x;
}
document.write(add(43, 23) + "</br>" );
document.write(add(43, -23) + "</br>" );
</script>
|
Output:
66
20
Time Complexity: O(y)
Auxiliary Space: O(1)
Thanks to Gaurav Ahirwar for suggesting the above solution.
Share your thoughts in the comments
Please Login to comment...