Castle

我的沉思、笔记和回忆

根据15位身份证号或者身份证号前17位获取完整身份证号

技术

根据15位身份证号或者身份证号前17位获取完整身份证号从而完成身份证号是否有效的校验。

javascript 写法:

//javascript
function getIDCard(str){
    let modulus = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    let mods = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2', '1']
    if(str.length == 15){
        str = str.substr(0,6) + "19" + str.substr(6, str.length - 6)
    }
    let total = 0
    modulus.forEach(function(value, index){
        total += value * str[index]
    })
    return str + mods[total % 11]
}

go 写法:

func getIDCard(str string) string {
    modulus := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
    mods := []rune{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2', '1'}
    if len(str) == 15 {
        str = str[:6] + "19" + str[6:]
    }
    total := 0
    for i, v := range modulus {
        strHere, _ := strconv.Atoi(string(str[i]))
        total += v * strHere
    }

    return str + string(mods[total%11])
}
创建于2017年06月26日 13:28
阅读量 543
留言列表

暂时没有留言

添加留言