CodingTour
ARTS #159

Algorithm

本周选择的算法题是:Number of 1 Bits

规则

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Note:

  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Constraints:

  • The input must be a binary string of length 32.

Solution

struct Solution {} 

impl Solution {
    // pub fn hammingWeight (n: u32) -> i32 {
    //     n.count_ones() as i32
    // }
    
    pub fn hammingWeight (mut n: u32) -> i32 {
        let mut ans = 0;
        for _ in 0..32 {
            ans += (n & 1) as i32;
            n >>= 1;
        }
        ans
    }
}

Review

Why I started Rust instead of stick to Python

估计作者也预料到了这样的文章很容易引入语言之争,所以一开始就先说了 “不是说哪种语言更好”,不过通篇下来确实感觉这些对比的例子不是特别好。

毫无疑问 Rust 是一门很有前途的语言,性能快、内存安全、拥有强大的模板,但这些对比出来的“优势”并不能与 Python 竞争,比如对于大多数涉及数据库访问和用户交互的程序来说,语言速度通常不是首要问题;鸭子类型是 Python 的特征之一,说其是问题不太合适。

不过有些语言确实更适合繁重的计算,但通常不能简单的从 codebase 规模角度去辩证什么语言表现的会更好。

Tip

Rust 默认是 move 语义;如果实现了 copy trait,则默认为 copy 语义;clone 是基于语义的复制,比如 Box 类型是深度复制,Rc 类型则是增加引用计数。

Share

分享一个终端“插件”:Fig

它目前的核心功能是为终端提供 IDE 风格的自动完成:

Fig 完全兼容 iTerm、VSCode、Jetbrains 等应用。

它的新手引导设计的非常不错:

感觉是一家非常重视技术和产品细节的公司,其实该产品孵化自鼎鼎大名的 Y Combinator,背后还有 Jason Warner (前 GitHub CTO)、Adam Gross (前 Heroku CEO)、Scott Belsky (Adobe CPO) 等的支持,虽然它现在只是一个自动完成,但 Fig 的野心却是建立一个类似于苹果 App Store 的终端商城,自动完成只是他们第一个 app 而已。