[C++] [Java] Clean Code


  • 2

    1st number has to be a multiplier.
    2nd number has to be a divisor.
    Every number after though, can be effectively multipliers if divide the 2nd number. like this:
    a / (b / c / d / e / f)
    is the same as:
    a / b * c * d * e * f
    C++

    class Solution {
    public:
        string optimalDivision(vector<int>& nums) {
            int n = nums.size();
            string expr;
            for (int i = 0; i < n; i++) {
                if (i > 0) {
                    expr += "/";
                }
                if (i == 1 && n > 2) {
                    expr += "(";
                }
                expr += to_string(nums[i]);
                if (i == n - 1 && n > 2) {
                    expr += ")";
                }
            }
            return expr;
        }
    };
    

    Java

    public class Solution {
        public String optimalDivision(int[] nums) {
            int n = nums.length;
            String expr = "";
            for (int i = 0; i < n; i++) {
                if (i > 0) {
                    expr += "/";
                }
                if (i == 1 && n > 2) {
                    expr += "(";
                }
                expr += nums[i];
                if (i == n - 1 && n > 2) {
                    expr += ")";
                }
            }
            return expr;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.