18/05/2023 8:33 am
Topic starter
Notifications
Clear all
How to add two numbers without using the plus operator in Java?
0
How to add two numbers without using the plus operator in Java?
Answer
Add a comment
Add a comment
1 Answer
0
18/05/2023 10:23 am
To add two numbers without using the plus operator in Java, you can use the concept of bitwise operations and arithmetic.
Here’s an example of how you can achieve this using bitwise operations:
public class AddNumbersWithoutPlusOperator { public static int addNumbers(int a, int b) { while (b != 0) { int carry = a & b; // Calculate the carry a = a ^ b; // Add the numbers without considering the carry b = carry << 1; // Left shift the carry to add to the next bit } return a; } public static void main(String[] args) { int num1 = 7; int num2 = 5; int sum = addNumbers(num1, num2); System.out.println("Sum: " + sum); } }
Add a comment
Add a comment
Forum Information
- 14 Forums
- 1,836 Topics
- 5,052 Posts
- 0 Online
- 1,078 Members
Our newest member: Richardnop
Latest Post: loli
Forum Icons:
Forum contains no unread posts
Forum contains unread posts
Topic Icons:
Not Replied
Replied
Active
Hot
Sticky
Unapproved
Solved
Private
Closed