ptmdmusique

CLB_CodingChallenge_6_5_2018_V2

May 7th, 2018
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. /*Problem description
  2. Given N natural number(s), separate 0's and bring them to the left side of the containers.
  3. Time Complexity  : O(n)
  4. Memory Complexity: O(1)
  5. */
  6.  
  7. #include <iostream>
  8. using namespace std;
  9.  
  10. int main() {
  11.     int* storage;           //Use dynamic allocated array
  12.     int numOfNum;           //Number of input(s)
  13.  
  14.     //Take in the input and display it
  15.     cin >> numOfNum;
  16.     storage = new int[numOfNum];
  17.     for (int indx = 0; indx < numOfNum; indx++) {
  18.         cin >> storage[indx];
  19.     }
  20.     //Display the initial list
  21.     cout << "Your initial list: ";
  22.     for (int indx = 0; indx < numOfNum; indx++) {
  23.         cout << storage[indx] << " ";
  24.     }
  25.     cout << endl;
  26.  
  27.     //Go from the last index to the first one, shift all the non zero to the right most position
  28.     //  (next to another right most or end of the array)
  29.     int lastZeroPos = -1;   //The index of the last 0 position
  30.     //First, find the position of the last 0
  31.     for (lastZeroPos = numOfNum - 1; lastZeroPos >= 0 && storage[lastZeroPos] != 0; lastZeroPos--);
  32.     if (lastZeroPos <= 0) {
  33.         //Nothing to shift
  34.         cout << "Your list doesn't need to be shifted!" << endl;
  35.     } else {
  36.         //Then shift
  37.         for (int indx = lastZeroPos - 1; indx >= 0; indx--) {
  38.             //If we encounter something non-zero then...
  39.             if (storage[indx] != 0) {
  40.                 //Swap!
  41.                 storage[lastZeroPos--] = storage[indx];
  42.                 storage[indx] = 0;
  43.             }
  44.         }
  45.         //And, finally, re-display
  46.         cout << "Your shifted list: ";
  47.         for (int indx = 0; indx < numOfNum; indx++) {
  48.             cout << storage[indx] << " ";
  49.         }
  50.         cout << endl;
  51.     }
  52.  
  53.     delete[] storage;                   //Delete after you play!
  54.     return 0;
  55. }
Add Comment
Please, Sign In to add comment