Absolute difference as long

Absolute difference as long

Easy Java Data Types 25 views
Explanation Complexity

Problem Statement

Task: return absolute difference between two ints as a long (avoid overflow).

Input Format

Two integers a and b.

Output Format

A long value: absolute difference between a and b.

Example

2147483647 - (-2147483648)
4294967295

Constraints

• a and b are valid integers

• Must avoid integer overflow

Concept Explanation

If we subtract directly using int, overflow can happen.
So we first convert both numbers to long, then subtract,
and finally take absolute value.

Step-by-Step Explanation

1.Read integers a and b.

2.Convert both to long:

• long x = a

• long y = b

3.Compute diff = x - y.

4.If diff < 0, make it positive (-diff).

5.Return diff.

Concept Explanation

If we subtract directly using int, overflow can happen.
So we first convert both numbers to long, then subtract,
and finally take absolute value.

Step-by-Step Explanation

1.Read integers a and b.

2.Convert both to long:

• long x = a

• long y = b

3.Compute diff = x - y.

4.If diff < 0, make it positive (-diff).

5.Return diff.

Input / Output Format

Input Format
Two integers a and b.
Output Format
A long value: absolute difference between a and b.
Constraints
• a and b are valid integers

• Must avoid integer overflow

Examples

Input:
2147483647 - (-2147483648)
Output:
4294967295

Example Solution (Public)

Java
static long absDiff(int a,int b){long x=a;long y=b;long d=x-y;return d<0?-d:d;}

Official Solution Code

static long absDiff(int a,int b){long x=a;long y=b;long d=x-y;return d<0?-d:d;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.