Skip to content

Instantly share code, notes, and snippets.

@DogPawHat
Created August 1, 2022 20:46
Show Gist options
  • Save DogPawHat/31928050076a68e12713648d1322a9cb to your computer and use it in GitHub Desktop.
Save DogPawHat/31928050076a68e12713648d1322a9cb to your computer and use it in GitHub Desktop.
Cassidoo's number of ones in C++ for some reason
#include <iostream>
int numberOfOnes(int val)
{
int count = 0;
// only one digit
auto numberOfOnesCount = [&count](auto& self, int subval)->void {
if (subval < 10) {
if (subval == 1) {
count++;
}
}
else {
int base10Val = subval / 10;
int base1Val = subval % 10;
if (base1Val == 1) {
count++;
}
self(self, base10Val);
}
};
for (int i = 1; i <= val; i++) {
numberOfOnesCount(numberOfOnesCount, i);
}
return count;
}
int main()
{
std::cout << numberOfOnes(14); // 7
std::cout << "\n";
std::cout << numberOfOnes(5); // 1
std::cout << "\n";
std::cout << numberOfOnes(56); // 16
std::cout << "\n";
std::cout << numberOfOnes(152); // 89
std::cout << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment