F#实现——计算一个字符的Ascii码中1的个数

在做这个面试题之前,我们需要了解一下关于Ascii码的一些知识:

  •   0~31及127(共33个)是控制字符或通信专用字符(其余为可显示字符)
  •   32~126(共95个)是字符(32sp是空格),其中48~57为0到9十个阿拉伯数字
  •   65~90为26个大写英文字母,97~122号为26个小写英文字母,其余为一些标点符号、运算符号等
  •   后128个称为扩展ASCII码,目前许多基于x86的系统都支持使用扩展(或“高”)ASCII。扩展ASCII 码允许将每个字符的第8 位  用于确定附加的128 个特殊符号字符、外来语字母和图形符号

Ok,知道这些后,先把代码贴出来:

module CountNumberOneInChar

let countsOfOneInChar(cChar : char) =
    //get the Ascii of cChar
    let ascOfcChar = int(cChar)
    match ascOfcChar with   
    | illegal when illegal < 0 || illegal >127 
                -> failwith "illegal char..."
    | _ -> ()
    //used to count the number of 1
    let mutable count = 0

    for i in [1..7] do
        //shift i bits every time, ues And operation to cut the overflowed bits.
        let leftShift = (ascOfcChar <<< i) &&& 128
        //compare to 127 which is corresponding to 01111111
        if(leftShift > 127) then
            count <- count + 1
    count

其中比较关键的是let leftShift = (ascOfcChar <<< i) &&& 128 这一句,先左移i位,在将超出后8位的位消0,也就是与128(00000000 10000000)做与操作。

Ok,试一下:

let xx = countsOfOneInChar 'a'

运行结果:

val xx : int = 3

貌似没什么问题。。。。 做个笔记 ~:)

posted @ 2012-11-10 12:38  ZackZhou  阅读(1238)  评论(1编辑  收藏  举报