0

I'm trying to implement bignum division by powers of 10. Specifically, this is a kattis problem: https://open.kattis.com/problems/divideby100

I believe my answer is correct but I get a time limit exceeded warning. I know it's due to the insert function I keep using. My question is, what, if any, are faster alternatives to insert? Or am I crazy and just going about this problem all wrong by treating the input as strings?

#include <cstdlib>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <string>
#include <algorithm>

using namespace std;

int main(){
    string N;
    string M;

    getline(cin, N);
    getline(cin, M);


    long long MSize = M.size();
    long long NSize = N.size();
    long long zeroesInM = MSize - 1;

    if(NSize >= MSize){
        N.insert(NSize - zeroesInM, ".");
        NSize++;
    }else{
        long long zeroesInN = N.size() - 1;
        for(long long i = 0; i < zeroesInM - zeroesInN - 1; i++){
            N.insert(0, "0");
            NSize++;
        }
        N.insert(0, ".");
        N.insert(0, "0");
        NSize += 2;

    }


    long long numTrailingZeros = NSize;
    while (N[numTrailingZeros - 1] == '0'){
            numTrailingZeros--;
    }
    numTrailingZeros = NSize - numTrailingZeros;
    N.erase(NSize-numTrailingZeros, numTrailingZeros);
    NSize -= numTrailingZeros + 1;

    if(N[NSize] == '.'){
        N.erase(NSize);
    }

    cout << N << endl;
    return 0;
}
  • 2
    If your code works, and you only want to increase its performance, consider asking on [codereview.stackexchange.com](https://codereview.stackexchange.com/). – Algirdas Preidžius Mar 03 '18 at 09:41
  • Nothing wrong with using strings but don't feel that you have to *manipulate* strings or that you have to perform only a single output. Once you've read the input you should be able to do the output in stages without any futher string manipulation. That's my intuition anyway. – john Mar 03 '18 at 09:45
  • Hmm that's a good point. I'll try that and re-implement. – user2953932 Mar 03 '18 at 09:46
  • you don't need to do any maths to divide a number by 10^n, just shifts the decimal point appropriately, i.e. some simple string manipulation – phuclv Mar 03 '18 at 10:11
  • 1
    @john THAT WAS IT. I fixed it thanks to your suggestion. Turns out I was drastically overthinking the problem. Thank you! – user2953932 Mar 03 '18 at 10:25

0 Answers0