0

I have been working on this code for 3 days now and I can't figure out how to remove zeros before the output.

It is a program which calculates factorial of a number. Even if I use if statement as you can see which is commented it removes zeros after and between the numbers. I even tried to take size as the initial value for a but it just takes the global value, but not from the while loop, I even tried to store its value in another variable then also its not working.

#include <bits/stdc++.h>
#include <iostream>

using namespace std;

// Complete the extraLongFactorials function below.
void extraLongFactorials(int n) {
  int arr[500] = {0};
  int size = 1, i = 0, carry = 0, temp = 0;
  arr[0] = 1;
  for (int j = 1; j <= n; j++) {
    for (int k = 0; k < 500; k++) {
      temp = arr[k] * j + carry;
      arr[k] = temp % 10;
      carry = temp / 10;
    }
    while (carry) {
      size++;
      arr[size] = carry % 10;
      carry %= 10;
    }
  }

  for (int a = 499; a >= 0; a--) { // if(arr[a]!=0)
    cout << arr[a];
  }
}

int main() {
  int n;
  cin >> n;
  cin.ignore(numeric_limits<streamsize>::max(), '\n');

  extraLongFactorials(n);

  return 0;
}
Biffen
  • 6,249
  • 6
  • 28
  • 36
Rahul
  • 11
  • 3
    (OT: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice).) – Biffen May 23 '19 at 12:47
  • You need two loops. The first skips the leading zeros, and the second writes the remaining values. Or you could add a flag that indicates whether you're skipping leading zeros; while the flag is true you don't write any output. When you hit a non-zero value, set the flag to false. – Pete Becker May 23 '19 at 19:19

1 Answers1

1

Just skip the leading zeros by finding out the index of the first non-zero value:

i = 499;

// Skip leading zeros.
while (i > 0 && arr[i] == 0) {
    --i;
}

while (i >= 0) {
    cout << arr[i--];
}

Also, please don't #include <bits/stdc++.h>. This is a private, compiler specific header that you are not supposed to include.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96