当前位置:网站首页>[leetcode] small thinking of optimal division

[leetcode] small thinking of optimal division

2022-06-12 19:55:00 PushyTao

Topic link

 Insert picture description here

If there is only one number, you can directly return that number
If there are two numbers , The answer is “a/b”
If it is more than three numbers {
To maximize results , So let's make the divisor smaller . In the case of integers , Division only makes the number smaller and smaller , So put all the numbers except the first one in brackets , such as :
a/(b/c/d/…/f)
}

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

版权声明
本文为[PushyTao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202281528226268.html