Math Problem on LC

This problem is a simple math one on Leetcode: Find Three Consecutive Integers That Sum to a Given Number - LeetCode

"Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array."

Call the 3 consecutive numbers N, N+1 and N+2. Hence:

N+N+1+N+2 = num
3N+3 = num
N = (num-3)/3

With that, the solution becomes straightforward - one-liner:

return (num - 3) % 3 != 0 ? new long[] { } : new long[] { (num - 3) / 3, (num - 3) / 3 + 1, (num - 3) / 3 + 2 };

Cheers, ACC




Comments

Popular posts from this blog

Changing the root of a binary tree

ProjectEuler Problem 719 (some hints, but no spoilers)

The Power Sum, a recursive problem by HackerRank