Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
How can I remove all the trailing zeros in a long?
e.g. 450000000 to 45, 2100 to 21
all numbers are positive if that makes any difference.
With the help of modulo 10 , you can do this
void removeTrailingZeros(long& n)
{ while (n % 10 == 0) n /= 10; }
First you need a more precise definition of trailing zeros. In a decimal representation, “a trailing zero” means “divisibility by 10”. (Similarly, you would consider divisibility by 2 for binary or by 16 for hexadecimal.) A number is divisible by 10 when the remainder after division by 10 (the result of the modulo (%) operation) is zero. To “trim trailing zeros” from a number in this sense, you would divide the number by the desired base as many times as needed, until it is no longer divisible by the base.
uint64_t trim_zeros(uint64_t number, const uint64_t base = 10) {
if (number == 0) return 0; // or maybe throw something
while (number % base == 0) number /= base;
return number;
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
need an programming logic to print an 4 decimal points
EX: scalar should be 0 to -5
value = 10006 , scalar = -3 then print result = 10.0060 (4 decimals)
value = 123 ,scalar = -5 then print result = 0.0012 (4 decimals)**
required value/divisor = 10 , value%divisor = 0060 (required logic after decimals )
I tried like this:
divisor = std::pow(10,std::abs(scalar));
**Result = snprintf(X,Y,"%d.%0*d",value/scalar,4,value%scalar);**
I'm not allowed to use float , setprecision() .
It does not necessarily represent the actual value , but we can format that value to print with logic like the original one (by using the logic , add ...subtract...pow etc)
std::int32_t divisor = static_cast(std::pow( 10.0F, std::abs( Scalar)) );
but int the above result modulus scalar value with 0 are not considering.
**Please provide me the logic to print the above result with scalar condition
In order to print decimals (easily), you need floating point:
printf("%10.6f", static_cast<double>(1) / 3);
If one of the arguments to division is floating point, the compiler will promote the expression to floating point.
Integral or scalar division will lose decimals.
You are always welcome to write your own division function.
Edit 1: Shifting
You don't need to use the pow function (especially since it's floating point).
Use a loop, in the loop multiply your divisor by 10 each time.
double result = (double) scalar / value;
int divisor = 10;
int i;
for (i = 0; i < NUMBER_OF_DECIMALS; ++)
{
// Isolate a digit using math.
// print the digit
divisor += 10;
}
The math part is left as an exercise for the OP.
In this homework exercise you are expected to perform your own number formatting, rather than using that of a library.
For instance, to format and output 100 as "100"
int accum = 100;
int position = 0;
while (accum > 0)
{
printf("%d", accum % 10);
accum /= 10;
position += 1;
}
For your homework assignment, you need to modify the above loop so that it puts a printf(".") in the correct place in the output number. Your answer is likely to involve multiplying accum before the loop and testing position relative to scalar
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am interested in understanding the implementation of converting decimal to binary. Could somebody clarify the purpose of using left-shift and Right-shift in the following code?
void static inline unsignedToBinary(unsigned x, char*& bin)
{
bin = (char*) malloc(33);
int p = 0;
for (unsigned i = (1 << 31); i > 0; i >>= 1)
bin[p++] = ((x&i) == i) ? '1' : '0';
bin[p] = '\0';
}
This is a straightforward implementation of binary conversion that uses bit operations.
Variable i represents the mask - an int containing 2k value, where k is the position of the bit.
The initial value is 231, produced with left-shifting 1 by 31.
for loop uses >>= 1 to right-shift the mask until 1 gets shifted out of it, making i == 0.
At each iteration x&i is compared to i. The comparison succeeds when x contains 1 in the position where i has its 1; it fails otherwise.
Note: Although using malloc in C++ is certainly allowed, it is not ideal. If you want to stay with C strings, use new char[33] instead. A more C++-like approach would be using std::string.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Hi i'm stuck on my assignment which partly requires me to find the nth tetrahedral number mod m. Tetrahedral numbers are the sum of the all the n previous triangle numbers and are denoted by the formula (n(n+1)(n+2))/6. Given that i am supposed to find the modulo of the number and that the nth triangular number can exceed the size of a long long int, may i know is there a method to calculate this or another way to find the nth tetrahedral number? The modulo m can reach up to 100000 so i'm not sure if pascal's triangle will work here. Thank you.
Modular arithmetic has the property that
(a*b) % m == ((a % m) * (b % m)) % m
You can use that equivalence to keep your numbers in a range of standard integer types. You should take care when you divide the sum by 6, though, because the modulo equivalence isn't necessarily true for division. You can circumvent this by calculating everything modulo 6*m first and then take everything modulo m.
Your calculations must be able to multiply two numbers modulo m safely. Here, you need at most (6 · 100,000)², which fits into a 64-bit integer, but not in a 32-bit integer:
std::uint64_t tetra_mod(std::uint64_t n, std::uint64_t m)
{
std::uint64_t m6 = 6*m;
std::uint64_t n0 = n % m6;
std::uint64_t n1 = (n + 1) % m6;
std::uint64_t n2 = (n + 2) % m6;
return (n0 + n1 + n2) % m6 / 6 % m;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Given an int variable, I would like to check if the number of '1' in its binary representation is even or odd. It can be made with xor operations like
int n;
int s = 0;
for(;n;n>>=1)
s ^= (n&1);
There's some better way to do so in C++?
Note: I'm not asking for the number of '1's, but for its parity, so I thought there could be some better code than mine.
uint32_t v = somevalue;
v ^= v >> 1;
v ^= v >> 2;
v = (v & 0x11111111U) * 0x11111111U;
bool parity = (v >> 28) & 1;
From https://graphics.stanford.edu/~seander/bithacks.html
It has a 64bit variant too.
For clarification, with "parity" I don't mean if the number is even or odd mathematically, but if the count of 1 bits in it's binary representation is even or odd; like described in https://en.wikipedia.org/wiki/Parity_bit. With the maths meaning, the code in the question makes no sense, so I assumed OP means the same. The statement
I'm not asking for the number of '1's, but for its parity
then means that he/she just wants to know if the 1 count is even or odd,
but not the exact number of 1's.
If you are really after speed, you can tabulate the number of bits (or just its parity) for all byte values 0..255. Then mapping a union on the variable or using shifts/masks, accumulate for the four bytes.
Even faster and more paranoid, tabulate for all short values 0..65535.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
We are given a integer number, and the task is to tell whether the binary representation of the number includes equal number of binary 1's and 0's or not?
I want the solution in constant time.
I have the code for calculating no of 1s with the help of hamming weight algorithm!
Please help i want to count no of 0's!!
In production code (I mean if not restricted by rules dictated in an assignment) I'd do it like this:
#include <iostream>
#include <bitset>
int main()
{
int k(24); // an example integer - the one you check for equality of 0's and ones
std::bitset<32> bs(k); // I suppose 32 bit numbers - choose your own length
if ( 16 == bs.count() ) // 16 is half the bit length - count returns the bits that are swithced ON
{
std::cout << "Equal number of 1s and 0s\n";
}
}
I mean after all the question is tagged c++
If x - is your number, N1 is the number of "1" then
int N0 = ceil(log2(x)) - N1;
will calculate number of "0". Do not forget
#include <math.h>
int numberOfZeros = numberOfBinaryDigits - numberOfOnes;
Where number of binary digits is either based on the storage used for the data, or log2.
32 bit integer examples:
Using bit operators (and multiply):
int bitcount(unsigned int i)
{
// generate a bit count in each pair of bits
i = i - ( (i >> 1) & 0x55555555);
// generate a bit count in each nibble
i = (i & 0x33333333) + ( (i >> 2) & 0x33333333 );
// sum up the bits counts in the nibbles
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
Using gcc popcount:
int bitcount(unsigned int i)
{
return(__builtin_popcount(i));
}
using visual studio popcnt:
int bitcount(unsigned int i)
{
return(_popcnt(i));
}
// if(16 == bitcount(i)), then equal number of 1's and 0's.