Write a program to subtract two numbers without using the '-' operator.
Example 1:
Input:a=7,b=8
Output:a=-1
Approach 1: Iterative
Java
public class TwoNumberSubtraction {public static void main(String[] args) {int a = 7;int b = 8;int sum = subWithoutOperator(a, b);System.out.println(sum);}// debug for given example: a=7, b=8private static int subWithoutOperator(int a, int b) {while (b != 0) {// 7=0111, 8=1000, ~7=1000 then ~a & b=8int borrow = ~a & b;// 7=0111, 8=1000 then a ^ b=1111a = a ^ b;// b=borrow*2;b = borrow << 1;}return a;}}
C++
#include <bits/stdc++.h>using namespace std;//function to subtract number//without using '-' operatorint subtractWithoutOperator(int a,int b){while(b!=0){int borrow=~a&b;a=a^b;//b=borrow*2b=borrow<<1;}return a;}int main(){int a=7,b=8;int subtract=subtractWithoutOperator(a,b);cout<<"Subtract is ";cout<<subtract<<"\n";return 0;}
Approach 2: Recursive
Java
public class TwoNumberSubtraction {public static void main(String[] args) {int a = 7;int b = 8;int sum = subWithoutOperatorRecursion(a, b);System.out.println(sum);}private static int subWithoutOperatorRecursion(int a, int b) {if (b == 0)return a;elsereturn subWithoutOperatorRecursion(a ^ b, (~a & b) << 1);}}
C++
#include <bits/stdc++.h>using namespace std;//function to subtract number//without using '-' operatorint subtractWithoutOperatorRecursive(int a,int b){if(b==0)return a;return subtractWithoutOperatorRecursive(a^b,(~a&b)<<1);}int main(){int a=7,b=8;int subtract=subtractWithoutOperatorRecursive(a,b);cout<<"Subtract is ";cout<<subtract<<"\n";return 0;}
No comments:
Post a Comment