Safe average without overflow

Safe average without overflow

Medium Java Data Types 23 views
Explanation Complexity

Problem Statement

Task: return average of two ints without overflow.

Input Format

Two integers a and b.

Output Format

An integer: average of a and b without overflow.

Example

2147483647 2147483647
2147483647

Constraints

• a and b are valid integers

• Must avoid overflow

Concept Explanation

If we calculate (a + b) / 2, overflow may happen.
So we use a safe formula:

a + (b - a) / 2


This avoids adding two large numbers directly.

Step-by-Step Explanation

1.Read integers a and b.

2.Compute result = a + (b - a) / 2.

3.Return result.

Concept Explanation

If we calculate (a + b) / 2, overflow may happen.
So we use a safe formula:

a + (b - a) / 2


This avoids adding two large numbers directly.

Step-by-Step Explanation

1.Read integers a and b.

2.Compute result = a + (b - a) / 2.

3.Return result.

Input / Output Format

Input Format
Two integers a and b.
Output Format
An integer: average of a and b without overflow.
Constraints
• a and b are valid integers

• Must avoid overflow

Examples

Input:
2147483647 2147483647
Output:
2147483647

Example Solution (Public)

Java
static int safeAvg(int a,int b){return (int)(((long)a+(long)b)/2); }

Official Solution Code

static int safeAvg(int a,int b){return (int)(((long)a+(long)b)/2); }
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.