LeetCode 2417: Closest Fair Integer

MathEnumeration

LeetCode 2417 Solution Explanation

Explanation:

Given a positive integer n, we need to find the closest fair integer to n. A fair number is defined as a number that has the same number of odd and even digits when converted to a string. If n is already a fair number, we return n. Otherwise, we need to find the closest fair number to n.

To approach this problem, we can start by converting the given integer n into a string representation so that we can easily count the number of odd and even digits. Once we have the counts of odd and even digits, we can increment or decrement the number to find the closest fair number.

We will iterate over the digits of n from left to right. At each digit, we will consider two possibilities:

  1. If the digit is odd, we can try decrementing it until the number becomes fair.
  2. If the digit is even, we can try incrementing it until the number becomes fair.

We will keep track of the closest fair number found so far and update it whenever we find a closer one.

Finally, we return the closest fair number.

:

LeetCode 2417 Solutions in Java, C++, Python

class Solution {
    public long closestFair(int n) {
        String numStr = String.valueOf(n);
        int oddCount = 0, evenCount = 0;
        
        for (char c : numStr.toCharArray()) {
            if ((c - '0') % 2 == 0) {
                evenCount++;
            } else {
                oddCount++;
            }
        }
        
        long closestFair = n;
        for (int i = 0; i < numStr.length(); i++) {
            char c = numStr.charAt(i);
            if ((c - '0') % 2 == 0 && evenCount < oddCount) {
                closestFair = closestFair * 10 + 1;
                evenCount++;
            } else if ((c - '0') % 2 != 0 && oddCount < evenCount) {
                closestFair = closestFair * 10;
                oddCount++;
            } else {
                closestFair = closestFair * 10 + (c - '0');
            }
        }
        
        return closestFair;
    }
}

Interactive Code Editor for LeetCode 2417

Improve Your LeetCode 2417 Solution

Use the editor below to refine the provided solution for LeetCode 2417. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems