# leetcode 228. Summary Ranges

Posted by 111qqz on Friday, April 14, 2017

## TOC

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given `[0,1,2,4,5,7]`, return `["0->2","4->5","7"].`

``````/* ***********************************************
Author :111qqz
Created Time :2017年04月14日 星期五 16时26分01秒
File Name :228.cpp
************************************************ */
class Solution {

public:

string int2st(long long x)
{
if (x==0) return "0";
string ret = "";
int val;   //md还有负数
long long sign = 1;
if (x<0) sign = -1;
x*=sign;
while (x)
{
val = x % 10;
ret = ret + char(val+'0');
x/=10;
}
if (sign==-1) ret +="-";
reverse(ret.begin(),ret.end());
return ret;
}
string solve(vector<int>& vec)
{
string ret = "";
int siz = vec.size();
if (siz==1) ret = ret + int2st(vec[0]);
else ret = ret + int2st(vec[0]) + "->" + int2st(vec[siz-1]);
return ret;
}
vector<string> summaryRanges(vector<int>& nums) {
int siz = nums.size();
vector<string>res;
if (siz==0) return res;
vector<int>tmp;
for ( int i = 0 ; i < siz ; i++)
{
if (tmp.size()==0)
{
tmp.push_back(nums[i]);
}else if (nums[i]==nums[i-1]+1)
{
tmp.push_back(nums[i]);
}else
{
res.push_back(solve(tmp));
tmp.clear();
tmp.push_back(nums[i]);
}
}
res.push_back(solve(tmp));

return res;

}

};
``````

「真诚赞赏，手留余香」