How to quickly determine how many digits in an int? [duplicate] - c++

This question already has answers here:
Finding the length of an integer in C
(29 answers)
Closed 9 years ago.
I know I can do:
n = floor(log10(i)) + 1;
Or I can do a quick loop:
while(i) {
n++;
i/=10;
}
Is there any better way than a complicated math operation, or a loop to achieve the goal? For example: if i = 1234, then n = 4.

The shortest way I know of (not computationally, just in terms of typing) is to call snprintf(3):
int n = snprintf(NULL, 0, "%d", i);

convert it to a string (itoa) and count the number of characters? (might be not the best performance-wise though)

Related

How to fix rand()/RAND_MAX in a method that always produces 0.0000000? [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Integer division always zero [duplicate]
(1 answer)
Random number c++ in some range [duplicate]
(6 answers)
Closed 3 years ago.
I need to produces numbers between 0 and a max (seen in code as assetMax). In the code, the rand()/RAND_MAX always produces 0 and I cannot seem to figure out why. I use the rand() function immediately before it to produce values in a range and it works completely fine. However, here it does not.
I have tried to switch the order of the variables, create the random number in a separate double before multiplying the two, and the header.
void cPortfolio::randomize(cProblem &portfolioProblem) {
int assetCount = 6 * rand() / RAND_MAX + (portfolioProblem.assetMax-8); //this line works as expected
int test;
for (int i = 0; i < assetCount; i++) {
double num = rand() / RAND_MAX; //this always produces 0.0000
int test = num * (portfolioProblem.assetNum); } `} //cannot format these correctly please ignore the brackets

C++ Random doubles from -1 to 1 [duplicate]

This question already has answers here:
generate random double numbers in c++
(10 answers)
Closed 4 years ago.
I need to randomly generate numbers (using random()) from -1 to 1 that are doubles. For example the output would be something like:
1,
-0.3324,
0.7821,
0.9823,
-0.111
etc... this is what I was trying to do walk_Length = (double)rand()%2 - 1;
You might get away with something like
double walk_Length = static_cast<double>(rand()) / RAND_MAX * 2 - 1;

Find the length of an integer in C++ [duplicate]

This question already has answers here:
C++ - how to find the length of an integer
(17 answers)
Closed 7 years ago.
In Java, I use
int length = String.valueOf(input).length();
to find the length of an integer.
My question is: Are there any similar ways to do so in C++?
I have already tried the for loops and while loops such as:
while (input > 0){
input/=10;
count++;
So, apart from the loops are there anything else available in C++. Thank you for your answer.
If you want an exact counterpart of what you have written in Java, you can use:
int length = to_string(input).length();
Note that to_string is a C++11 feature. Also, be careful with negative numbers.
The number of digits can be calculated without converting to a string first by using the number's logarithm:
std::size_t intlen(int i) {
if (i == 0) return 1;
else if (i < 0) return 2 + static_cast<std::size_t>(std::log10(-i));
else if (i > 0) return 1 + static_cast<std::size_t>(std::log10(i));
}
The logartihm is only defined for positive numbers, so negatives and zero have to be handled separately, counting the - sign as an additional character. Replace log10 by log2 to obtain the number of binary digits (this is possible for any base).
Note however that converting to strings first (e.g. by using std::to_string) is a locale-dependent operation and can thus yield different results for different language settings - some locales insert a thousands separator (e.g. 100,000) which will not show up using the above formula.
unsigned int number_of_digits = 0;
do {
++number_of_digits;
n /= base; } while (n);
// n is your base number.
Talking about pre-C++11, you can use the same approach, but with sprintf.
Convert integer to a char array, and then get its length:
char buffer[30];
int length = sprintf(buffer, "%d", input);
Here is the working IDEOne example.
Apart from the loops there is recursion. For example, for positive integers you can do:
unsigned int len(unsigned int n)
{
return n ? len(n/10)+1 : 0;
}

How to Set certain digits for generating random numbers in C++ [duplicate]

This question already has answers here:
How do I scale down numbers from rand()?
(9 answers)
Closed 8 years ago.
Hi. Is there any way to set the size of random numbers?( in random number generator "rand()")
For example I want to generate 10 digits random numbers.
and one more question, how can i set random function to generate numbers between 0 and 1 (for example 0100110110) ?
Im not sure about setting the size of the numbers. However I dont think it would be possible to get each digit to produce just a 0 or 1.
What you can do however is something like below:
ostringstream 10digitNumber;
for(int i = 0 ; i < 10 ; i ++){
v1 = rand() % 2;// generate o or 1
10digitNumber<< v1;// build up a string of 1 and 0
}
int real10DigitNumber = static_cast<int>10digitNumber); // typecast to integer
Please forgive me if my syntax isn't 100 %. Its being awhile since I used c++.

Collecting the 2-power decomposition of n (Python, C++) [duplicate]

This question already has answers here:
Base-2 (Binary) Representation Using Python
(2 answers)
Closed 9 years ago.
I am writing a quick program to decompose a number into powers of 2. Is this an efficient way to do it:
pows=[]
pos = 0
while n>0:
if n%2==1: pows.append(2**pos)
n/=2
pos+=1
I've written this in Python but I'm also interested in how it's done in C++.
I don't know if this is a "smart" way to do it or if it's considered horribly inefficient.
The most natural implementation in C++ would use a bit mask for
the powers of two, something like:
std::vector<unsigned> p2;
unsigned m = 1;
while ( m != 0 ) {
if ( (m & i) != 0 ) {
p2.push_back( m );
}
m <<= 1;
}
You certainly don't want to call the pow function each time in
the loop. A somewhat trickery way, which is likely faster
(since it will usually pass less times in the loop) would be:
std::vector<unsigned> p2;
std::cout << i << ": ";
while ( i != 0 ) {
unsigned n = i & i - 1;
p2.push_back( i ^ n );
i = n;
}
I would recommend the first (which is readily understandable)
unless the profiler really says you must use the second.
Any modern compiler is probably going to be smart enough to optimize this. Get your code to run correctly first, and worry about optimizing for speed after profiling (if it is too slow).