Created
May 4, 2023 21:15
-
-
Save kwk/7e408065ea291e49fea4a83cf90a9cdf to your computer and use it in GitHub Desktop.
getNumDisplayWidth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cmath> | |
#include <array> | |
static unsigned getNumDisplayWidth(unsigned N) { | |
if (N < 10) | |
return 1; | |
if (N < 100) | |
return 2; | |
if (N < 1000) | |
return 3; | |
if (N < 10000) | |
return 4; | |
if (N < 100000) | |
return 5; | |
if (N < 1000000) | |
return 6; | |
if (N < 10000000) | |
return 7; | |
printf("No source file should have more than 10 million lines"); | |
return 0; | |
} | |
static unsigned getNumDisplayWidth2(unsigned N) { | |
return ceil(log10(N+1)); | |
} | |
int main(int argc, char* argv[]) { | |
std::array<int, 14> Ns = {9, 10, 99, 100, 999, 1000, 9999, 10000, 99999, 100000, 999999, 1000000, 9999999, 10000000}; | |
for (auto N:Ns){ | |
printf("getNumDisplayWidth (%10d) = %d\n", N, getNumDisplayWidth(N)); | |
printf("getNumDisplayWidth2 (%10d) = %d\n", N, getNumDisplayWidth2(N)); | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getNumDisplayWidth ( 9) = 1 | |
getNumDisplayWidth2 ( 9) = 1 | |
getNumDisplayWidth ( 10) = 2 | |
getNumDisplayWidth2 ( 10) = 2 | |
getNumDisplayWidth ( 99) = 2 | |
getNumDisplayWidth2 ( 99) = 2 | |
getNumDisplayWidth ( 100) = 3 | |
getNumDisplayWidth2 ( 100) = 3 | |
getNumDisplayWidth ( 999) = 3 | |
getNumDisplayWidth2 ( 999) = 3 | |
getNumDisplayWidth ( 1000) = 4 | |
getNumDisplayWidth2 ( 1000) = 4 | |
getNumDisplayWidth ( 9999) = 4 | |
getNumDisplayWidth2 ( 9999) = 4 | |
getNumDisplayWidth ( 10000) = 5 | |
getNumDisplayWidth2 ( 10000) = 5 | |
getNumDisplayWidth ( 99999) = 5 | |
getNumDisplayWidth2 ( 99999) = 5 | |
getNumDisplayWidth ( 100000) = 6 | |
getNumDisplayWidth2 ( 100000) = 6 | |
getNumDisplayWidth ( 999999) = 6 | |
getNumDisplayWidth2 ( 999999) = 6 | |
getNumDisplayWidth ( 1000000) = 7 | |
getNumDisplayWidth2 ( 1000000) = 7 | |
getNumDisplayWidth ( 9999999) = 7 | |
getNumDisplayWidth2 ( 9999999) = 7 | |
No source file should have more than 10 million linesgetNumDisplayWidth ( 10000000) = 0 | |
getNumDisplayWidth2 ( 10000000) = 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment