Skip to main content
edited body
Source Link
coyotte508
  • 402
  • 2
  • 8

MORTAL gave a good answer on how to print the value of the number, but if you still want to compute the exact number of characters needed before, then:

int x =0;
while (dec>=x) {
    counter++;
    x = pow(2, counter);
}

This calculates the pow each time, it's a bit overkill.

Using your later approach would be more efficient:

unsigned x = dec;
do {
    counter++;
    x >>=2;>>=1; //Or x /= 2
} while (x > 0);

I also notice that although you tagged your code c++, the only c++ thing you're using is new[] and this could as easily be C code if you used malloc().

If you're doing C++, check out its standard library and notably things like std::vector, std::string and auto.

MORTAL gave a good answer on how to print the value of the number, but if you still want to compute the exact number of characters needed before, then:

int x =0;
while (dec>=x) {
    counter++;
    x = pow(2, counter);
}

This calculates the pow each time, it's a bit overkill.

Using your later approach would be more efficient:

unsigned x = dec;
do {
    counter++;
    x >>=2; //Or x /= 2
} while (x > 0);

I also notice that although you tagged your code c++, the only c++ thing you're using is new[] and this could as easily be C code if you used malloc().

If you're doing C++, check out its standard library and notably things like std::vector, std::string and auto.

MORTAL gave a good answer on how to print the value of the number, but if you still want to compute the exact number of characters needed before, then:

int x =0;
while (dec>=x) {
    counter++;
    x = pow(2, counter);
}

This calculates the pow each time, it's a bit overkill.

Using your later approach would be more efficient:

unsigned x = dec;
do {
    counter++;
    x >>=1; //Or x /= 2
} while (x > 0);

I also notice that although you tagged your code c++, the only c++ thing you're using is new[] and this could as easily be C code if you used malloc().

If you're doing C++, check out its standard library and notably things like std::vector, std::string and auto.

Source Link
coyotte508
  • 402
  • 2
  • 8

MORTAL gave a good answer on how to print the value of the number, but if you still want to compute the exact number of characters needed before, then:

int x =0;
while (dec>=x) {
    counter++;
    x = pow(2, counter);
}

This calculates the pow each time, it's a bit overkill.

Using your later approach would be more efficient:

unsigned x = dec;
do {
    counter++;
    x >>=2; //Or x /= 2
} while (x > 0);

I also notice that although you tagged your code c++, the only c++ thing you're using is new[] and this could as easily be C code if you used malloc().

If you're doing C++, check out its standard library and notably things like std::vector, std::string and auto.