zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    Python入门11 —— 基本数据类型的操作
    Win10安装7 —— 系统的优化
    Win10安装6 —— 系统的激活
    Win10安装5 —— 系统安装步骤
    Win10安装4 —— 通过BIOS进入PE
    Win10安装2 —— 版本的选择与下载
    Win10安装1 —— 引言与目录
    Win10安装3 —— U盘启动工具安装
    虚拟机 —— VMware Workstation15安装教程
    Python入门10 —— for循环
  • 原文地址:https://www.cnblogs.com/FsharpZack/p/2763880.html
Copyright © 2011-2022 走看看