Find the Exact Average of Two Integers

Solve this Problem
Easy10 min
Topics
Companies
Given two non-negative integers a and b, return their average as text with exactly two decimal places, for example "3.50". This problem exists to show type castingType CastingExplicitly converting a value from one type to another, e.g. (double) total turns an int into a double. at work. Dividing one int by another throws away the fractional part, so 7 / 2 quietly becomes 3. Casting one side to a doubledoubleA 64-bit floating-point type that can hold fractional values such as 3.5. first keeps the half. The first solution avoids decimals completely and rebuilds the answer from the whole part and the remainder; the second casts before dividing, which is the usual way to get an exact average.

Test Case 1:

Input:a = 3, b = 4
Output:"3.50"
Explanation:The sum 7 is odd, so the average has a half: 3.5, shown with two decimals.

Test Case 2:

Input:a = 10, b = 20
Output:"15.00"
Explanation:An even sum divides cleanly, but the answer still shows two decimal places.

Constraints

  • ◆0 ≤ a, b ≤ 1000000

Try the Dry Run

Approach & Solutions

Whole Part and RemainderGood

Stay in whole numbers the whole time. Integer division of the sum by 2 gives the whole part; the sum's remainder mod 2 says whether a half was dropped (1) or not (0). Attach ".50" or ".00" to the whole part. No decimals are ever computed, so nothing needs casting — this is how you would do it without any double type at all.

TimeO(1)
SpaceO(1)
class Solution { public String averageOfTwo(int a, int b) { int total = a + b; int whole = total / 2; int leftover = total % 2; String fraction = leftover == 1 ? ".50" : ".00"; return whole + fraction; } }
Cast to double Before DividingOptimal

Convert the sum to a double before dividing — an explicit type cast such as (double) (a + b). Once one operand is a double, the division keeps the fractional part. Then format the result with exactly two decimal places. Python's / already returns a float and JavaScript has only one number type, so float() and Number() just make the conversion visible.

TimeO(1)
SpaceO(1)
class Solution { public String averageOfTwo(int a, int b) { double average = (double) (a + b) / 2; return String.format("%.2f", average); } }

Related Problems