EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Write a program to minus two numbers without using minus operator

int a=5;b=2,c;
c=(a+(~b))+1
System.out.println(c);

c=(a+(~b))+1
==>(5+(-3))+1
==>(5-3)+1
==>(2)+1
=>3

import java.util.Scanner;

public class SubtractWithoutMinus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print(“Enter first number (a): “);
int a = sc.nextInt();

System.out.print(“Enter second number (b): “);
int b = sc.nextInt();

// Subtract b from a using bitwise operations
int result = add(a, negate(b));

System.out.println(“Result of a – b = ” + result);

sc.close();
}

// Function to add two integers using bitwise operations
public static int add(int x, int y) {
while (y != 0) {
int carry = x & y;
x = x ^ y;
y = carry << 1;
}
return x;
}

// Function to negate a number (get two’s complement)
public static int negate(int n) {
return add(~n, 1);
}
}

program to minus two numbers without using minus operator

Leave a Reply

Your email address will not be published. Required fields are marked *

EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Popular Courses

[Course Image]

Introduction to Programming

Learn the fundamentals of programming with Python in this beginner-friendly course.

12 Hours Beginner
[Course Image]

Data Science Essentials

Master the basics of data analysis, visualization, and machine learning.

20 Hours Intermediate
[Course Image]

Web Development Bootcamp

Build modern websites with HTML, CSS, JavaScript and popular frameworks.

30 Hours Beginner
[Course Image]

Digital Marketing Fundamentals

Learn SEO, social media marketing, email campaigns and analytics.

15 Hours Beginner
Educational Website Footer