Добавьте два числа, используя ++ и / или -

Опубликовано: 21 Января, 2022

Учитывая два числа, верните их сумму без использования операторов + и / или -, а также с использованием ++ и / или -.
Примеры:

 Ввод: x = 10, y = 5.
Выход: 15

Ввод: x = 10, y = -5.
Выход: 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++

// C++ program to add two numbers using ++
#include <bits/stdc++.h>
using namespace std;
 
// Returns value of x+y without using +
int add(int x, int y)
{
    // If y is positive, y times add 1 to x
    while (y > 0 && y--)
        x++;
 
    // If y is negative, y times subtract 1 from x
    while (y < 0 && y++)
        x--;
 
    return x;
}
 
int main()
{
    cout << add(43, 23) << endl;
    cout << add(43, -23) << endl;
    return 0;
}

Java

// java program to add two numbers
// using ++
 
public class GFG {
 
    // Returns value of x+y without
    // using +
    static int add(int x, int y)
    {
 
        // If y is positive, y times
        // add 1 to x
        while (y > 0 && y != 0) {
            x++;
            y--;
        }
 
        // If y is negative, y times
        // subtract 1 from x
        while (y < 0 && y != 0) {
            x--;
            y++;
        }
 
        return x;
    }
 
    // Driver code
    public static void main(String args[])
    {
        System.out.println(add(43, 23));
 
        System.out.println(add(43, -23));
    }
}
 
// This code is contributed by Sam007.

Python3

# python program to add two
# numbers using ++
 
# Returns value of x + y
# without using + def add(x, y):
     
    # If y is positive, y
    # times add 1 to x
    while (y > 0 and y):
        x = x + 1
        y = y - 1
     
    # If y is negative, y
    # times subtract 1
    # from x
    while (y < 0 and y) :
        x = x - 1
        y = y + 1
 
    return x
 
# Driver code
print(add(43, 23))
print(add(43, -23))
 
# This code is contributed
# by Sam007.

C#

// C# program to add two numbers
// using ++
using System;
 
public class GFG {
 
    // Returns value of x+y without
    // using +
    static int add(int x, int y)
    {
 
        // If y is positive, y times
        // add 1 to x
        while (y > 0 && y != 0) {
            x++;
            y--;
        }
 
        // If y is negative, y times
        // subtract 1 from x
        while (y < 0 && y != 0) {
            x--;
            y++;
        }
 
        return x;
    }
 
    // Driver code
    public static void Main()
    {
        Console.WriteLine(add(43, 23));
        Console.WriteLine(add(43, -23));
    }
}
 
// This code is contributed by Sam007.

PHP

<?php
// PHP program to add two
// numbers using ++
 
// Returns value of
// x+y without using +
function add($x, $y)
{
     
    // If y is positive,
    // y times add 1 to x
    while ($y > 0 && $y--)
       $x++;
 
    // If y is negative,
    // y times subtract
    // 1 from x
    while ($y < 0 && $y++)
       $x--;
 
    return $x;
}
 
    // Driver Code
    echo add(43, 23), " ";
    echo add(43, -23), " ";
 
// This code is contributed by ajit.
?>

Javascript

<script>
 
    // Javascript program to
    // add two numbers using ++
     
    // Returns value of x+y without
    // using +
    function add(x, y)
    {
   
        // If y is positive, y times
        // add 1 to x
        while (y > 0 && y != 0) {
            x++;
            y--;
        }
   
        // If y is negative, y times
        // subtract 1 from x
        while (y < 0 && y != 0) {
            x--;
            y++;
        }
   
        return x;
    }
     
    document.write(add(43, 23) + "</br>");
      document.write(add(43, -23) + "</br>");
     
</script>

Выход:

 66
20

Спасибо Гаураву Ахирвару за предложение вышеуказанного решения.
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше

Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

C