Integer to Char converting in String Compression


  • 0
    N
    class Solution{
        public:
            char *compressStr(char *str){
                int i, count, length = 1;
                char *strRep = str, tempChar;
        
                while(*(strRep++))
                    length++;
        
                char *charArray = new char[length];
                strRep = str;
                tempChar = *strRep;
                count = 0;
                i = 0;
                while(*strRep){
                    if(*strRep == tempChar){
                        count++;
                    }else{
                        charArray[i++] = tempChar;
                        if(count < 10)
                            charArray[i++] = count + '0';
                        else
                            pushNumInChar(charArray, count, &i);
                        tempChar = *strRep;
                        count = 1;
                    }
                    strRep++;
                    if(i >= length){
                        delete charArray;
                        return str;
                    }
                }
                charArray[i++] = tempChar;
                if(count < 10)
                    charArray[i++] = count + '0';
                else
                    pushNumInChar(charArray, count, &i);
                charArray[i++] = '\0';
                if(i >= length){
                   delete charArray;
                   return str;
                }
        
                return &charArray[0];
            }
        
            void printStr(char *str){
                while(*str != '\0')
                    cout << *(str++);
                cout << endl;
            }
        
        private:
            int calDigit(int number){
                int count = 1;
                while(number /= 10)
                    count++;
                return count;
            }
        
            void pushNumInChar(char charArray[], int number, int *posNum){
                int digitNum = calDigit(number) - 1;
                int tempNum;
                while(number){
                    tempNum = number / (int)pow(10, digitNum--);
                    charArray[(*posNum)++] = tempNum + '0';
                    number -= tempNum * (int)pow(10, digitNum + 1);
                }
            }
        };
    

    This is problem #1.5 from "cracking the coding interview", and the original answer is composed of java, since there exists a easier way to convert the number into string. Here I wrote the code in c++, I am sure about the correctness, however, is there any method to reduce the workload and make the answer simpler? Especially for the integer to char converting.

    My sincere gratitude for any comment!


Log in to reply
 

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