class Solution {\n public:\n vector countBits(int n) {\n vector bits(n + 1);\n int highBit = 0;\n for (int i = 1; i <= n; i++) {\n if (!(i & i - 1)) highBit = i;\n bits[i] = bits[i - highBit] + 1;\n }\n return bits;\n }\n };\n//转换为Swift内容:class Solution {\n func countBits(_ n: Int) -> [Int] {\n var bits = [Int](repeating: 0, count: n + 1)\n var highBit = 0\n for i in 1...n {\n if !(i & i - 1) {\n highBit = i\n }\n bits[i] = bits[i - highBit] + 1\n }\n return bits\n }\n}

C++ & Swift: Counting Bits in an Integer - Efficient Algorithm

原文地址: https://www.cveoy.top/t/topic/qbyq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录