ulvis.paste.net

Paste Search Dynamic
Recent pastes
getShortestLength
  1. #include<iostream>
  2. #include<string>
  3.  
  4. using namespace std;
  5.  
  6. int getShortestLength(int num);
  7.  
  8. int main() {
  9.     int input= -9;
  10.     cout << "Input: " << input << "\n\n";
  11.     cout << "Output: " << getShortestLength(input) << "\n\n";
  12.  
  13.    return 0;
  14. }
  15.  
  16. /** FUNCTION NAME: getShortestLength
  17. *   PURPOSE: To find the shortest possible palindrome based on the integer given.
  18. *   PARAMETER: int num
  19. *   RETURN VALUE: int rtnVal, length of shortest possible palindrome.
  20. *   FUNCTION SIGNATURE: int getShortestLength(int n)
  21. */
  22.  
  23. int getShortestLength(int num)
  24. {
  25.     string inputS = to_string(num);
  26.     int rtnVal = 0, len = (inputS.length()-1), lastDigit = 0;
  27.     bool alreadyPalind = 0;
  28.  
  29.     for(int i = 0; i<len; ++i)
  30.     {
  31.         if(inputS[i] == inputS[len-i])   alreadyPalind = 1;
  32.  
  33.         if(inputS[i] != inputS[len-i])
  34.         {
  35.             alreadyPalind = 0;
  36.             break;
  37.         }
  38.  
  39.     }
  40.  
  41.     if(num < -9)        //Any number less that -9 can not be a palindrome.
  42.         rtnVal = 0;
  43.     if((num>-10) && (num<10))    // Integers between -10 and 10 are a palindrome.
  44.         rtnVal = 1;
  45.     if(alreadyPalind == 1)      // Any palindrome can not be shorter than it is.
  46.         rtnVal = (inputS.length());
  47.     else
  48.         for(int i = 0; i< len; ++i)     //Finds the amount of duplicates at the end of an integer in order to count how many integer are not needed in the SHORTESt possible palindrome. EXAMPLE: 122, palindrome would 1221 and not 122221.
  49.         {
  50.             if(inputS[len] == inputS[len-i])
  51.             {
  52.                 lastDigit++;
  53.             }
  54.             if(i != 0 && inputS[len - i ] != inputS[len] && inputS[len - i] != inputS[len - i + 1])
  55.             {
  56.                 break;
  57.             }
  58.         }
  59.  
  60.         rtnVal =  ((inputS.length()) + (inputS.length()-lastDigit));
  61.  
  62.  
  63.         return rtnVal;
  64. }
  65.  
Parsed in 0.011 seconds