# My c++ solution with comments

• ``````class Solution {
private:
string intTostring(int num) {
vector<char> output;
string numString = "";
bool flag = false;
if (num < 0) { // flag to represent whether we should add a negative sign before the transformed string
flag = true;
}
if (num == 0) {
output.push_back(num+'0');
}
else {
while(num!=0){
output.push_back(abs(num%10)+'0'); // split the number into digits, and use abs in case the input is INT_MIN (negative/10=negative)
num = num/10;
}
}
if (flag == true) output.push_back('-');
for (int i=output.size()-1;i>=0;i--) {
numString += output[i];
}
return numString;
}
public:
vector<string> summaryRanges(vector<int>& nums) {
int start, end; // start/end element of the currently found sub-range
vector<string> result;
if (nums.size() == 0) {
return result;
}
if (nums.size() == 1) {
string range = intTostring(nums[0]);
result.push_back(range);
return result;
}
start = nums[0];
string range;
for (int i=1;i<nums.size();i++) {
if (nums[i] == nums[i-1] + 1) { // if the sequence is still continuous
if (i != nums.size()-1) continue; // if we haven't reach the end yet, then just continue
else if (i == nums.size()-1) { // if we are now at the end, then we've got the last sub-range now
end = nums[i];
range = intTostring(start)+"->"+intTostring(end);
result.push_back(range);
}
}
else { // if the sequence suddenly becomes un-continuous, then we should output the last sub-sequence we found
end = nums[i-1];
if (start != end) {
range = intTostring(start)+"->"+intTostring(end);
}
else {
range = intTostring(start);
}
result.push_back(range);
start = nums[i];
if (i == nums.size()-1) { // if we are now at the end, then the last element consists of the last sub-range
range = intTostring(start);
result.push_back(range);
}
}
}
return result;
}
};``````

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