Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- #include <cstdlib>
- // yeah this approach looks really unpleasant but it gets the job done much faster than log10
- // according to this: https://www.baeldung.com/java-number-of-digits-in-int
- std::uint8_t amountOfDigitsInInteger(const std::uint64_t integer) {
- std::uint8_t total = 0;
- std::uint64_t index = 1;
- while (index <= integer) {
- total += 1;
- index *= 10;
- }
- return total;
- }
- std::vector<std::uint8_t> getDigits(const std::uint64_t integer) {
- const std::uint8_t totalDigits = amountOfDigitsInInteger(integer);
- std::vector<std::uint8_t> digits(totalDigits);
- /*
- 69420 / 10000 -> 6
- 69420 / 1000 -> 69 % 60 -> 9
- 69420 / 100 -> 694 % 690 -> 4
- 69420 / 10 -> 6942 % 6940 -> 2
- 69420 / 1 -> 64920 % 69420 -> 0
- */
- std::uint64_t powerOfTen = 1;
- // powerOfTen = 10^totalDigits
- for (std::size_t index = 0; index < totalDigits - 1; index += 1) {
- powerOfTen *= 10;
- }
- std::uint64_t slice = integer / powerOfTen;
- std::uint64_t past = slice;
- digits[0] = slice;
- for (std::size_t index = 1; index < totalDigits; index += 1) {
- powerOfTen /= 10;
- slice = integer / powerOfTen;
- past *= 10;
- digits[index] = slice % past;
- past += digits[index];
- }
- return digits;
- }
- std::vector<std::uint8_t> getDigitsString(const std::uint64_t integer) {
- std::string digitsString = std::to_string(integer);
- std::vector<std::uint8_t> digits(digitsString.size());
- for (std::size_t index = 0; index < digitsString.size(); index += 1) {
- digits[index] = *(std::uint8_t*)&digitsString[index] - 48; // 48 is the ascii offset for numbers
- }
- return digits;
- }
- int main() {
- auto start = std::chrono::high_resolution_clock::now();
- constexpr std::size_t ITERATIONS = 10000;
- for (std::size_t index = 0; index < ITERATIONS; index += 1) {
- std::uint64_t random = static_cast<std::uint64_t>(rand()) << 32 | rand(); // generate a 64 bit integer;
- // for 10000 iterations averaged 0.84 seconds
- std::vector<std::uint8_t> d = getDigits(random);
- // for 10000 iterations averaged 0.86 seconds
- //std::vector<std::uint8_t> d = getDigitsString(random);
- for (std::size_t index = 0; index < d.size(); index += 1) {
- std::cout << (int)d[index] << std::endl;
- }
- }
- std::chrono::duration<double> elapsed = std::chrono::high_resolution_clock::now() - start;
- std::cout << "Time: " << std::to_string(elapsed.count()) << " seconds." << std::endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment