1

This is when going through a list of integers in order seperated by commas and I only print one instance of an integer even where there are more than one seperated by commas. (CodeEval challenge https://www.codeeval.com/open_challenges/29/)

My problem is I am trying to do this in linear time without any external storage. And I can't have a comma at the end (e.g. 1,3,4,6,). The solutions I found online all use some list to store the integers and then they do a print.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string str = "1,2,2,3,3,3,4,4";
    char c;
    int num = -1;
    for (int i = 0; i < str.length(); ++i) {
        if (str[i] == ',') continue;
        else {
            c = str[i]; 
            if ((c - '0') != num) {
                num = c - '0';
                cout << num << ",";
            } 
        }
    }
    cout << endl;        
    return 0;
}
Anton Savelyev
  • 762
  • 7
  • 22
  • 1
    You can print the comma in front of your number (except the first one) – MaxZoom Aug 02 '16 at 21:21
  • 1
    This answer may help: https://stackoverflow.com/questions/35858896/c-compare-and-replace-last-character-of-stringstream/35859132#35859132 – Galik Aug 02 '16 at 21:23

3 Answers3

3

One of the solution is to use boolean flag:

bool first = true;
for( ... ) {
    if( first ) first = false;
    else std::cout << ',';
    std::cout << data;
}
Slava
  • 43,454
  • 1
  • 47
  • 90
0
 if (i == str.length() - 1)
 {
     cout << num;
 }
 else 
 {
     count << num << ",";
 }
user2260040
  • 1,275
  • 1
  • 13
  • 26
-2

Or you could print a backspace at the end of the string processing:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string str = "1,2,2,3,3,3,4,4";
    char c;
    int num = -1;
    for (int i = 0; i < str.length(); ++i) {
        if (str[i] == ',') continue;
        else {
            c = str[i]; 
            if ((c - '0') != num) {
                num = c - '0';
                cout << num << ",";
            } 
        }
    }
    cout << '\b';
    cout << endl;        
    return 0;
}
Polb
  • 640
  • 2
  • 8
  • 21