Share my ugly cpp code


  • 0
    C
    class Solution {
    public:
        
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // use long long int to avoid overflow
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        string int2str(long long int i)
        {
            if(!i) return "0";
            
            string result;
            
            int sign = i<0 ? -1 : 1;
            i *= sign;
            
            while(i)
            {
                result.insert(result.begin(), i%10 + '0');
                i /= 10;
            }
            
            if(sign == -1) result.insert(result.begin(), '-');
            
            return result;
        }
        
        vector<string> summaryRanges(vector<int>& nums) 
        {
            vector<string> result;
            
            if( !nums.size() ) return result;
            
            int idx = 0;
            while(idx < nums.size())
            {
                if(idx+1 == nums.size())
                {
                    result.push_back( int2str(nums[idx]) );
                    break;
                }
                
                if(nums[idx+1] == nums[idx]+1)
                {
                    string s( int2str(nums[idx]) );
                    
                    idx++;
                    while(idx < nums.size() && nums[idx] == nums[idx-1]+1)
                        idx++;
                        
                    result.push_back( s + "->" + int2str(nums[idx-1]) );
                    continue;
                }
                
                result.push_back( int2str(nums[idx++]) );
            }
            
            return result;
        }
    };

Log in to reply
 

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