狐的传说
将它们存储在地图中,然后尝试您要查找其费用的号码。如果数字(键)不在地图中,则切断其最后一位数字并重复。这样,如果您找到匹配项,则可以保证这将是最长的前缀。这是一个示例查找函数:var prefixCostMap = map[uint64]float64{ 44: 0.01597, 447: 0.04958, 447530: 0.03, 447531: 0.048, 447532: 0.04950, 1: 0.1, 97: 0.1,}func lookup(num uint64) (longestPrefix uint64, cost float64, ok bool) { longestPrefix = num for longestPrefix > 0 { cost, ok = prefixCostMap[longestPrefix] if ok { break } longestPrefix = longestPrefix / 10 // Cut off last digit } return}测试它:fmt.Println(lookup(4475122112))fmt.Println(lookup(4475302112))fmt.Println(lookup(999))输出(在Go Playground上尝试):447 0.04958 true447530 0.03 true0 0 false注意:这不支持以 0 开头的数字。如果您还需要处理它,您可以将数字存储为字符串值,这样初始0数字将被保留。这是string版本的样子:var prefixCostMap = map[string]float64{ "44": 0.01597, "447": 0.04958, "447530": 0.03, "447531": 0.048, "447532": 0.04950, "1": 0.1, "97": 0.1, "0123": 0.05,}func lookup(num string) (longestPrefix string, cost float64, ok bool) { longestPrefix = num for longestPrefix != "" { cost, ok = prefixCostMap[longestPrefix] if ok { break } longestPrefix = longestPrefix[:len(longestPrefix)-1] // Cut off last digit } return}测试它:fmt.Println(lookup("4475122112"))fmt.Println(lookup("4475302112"))fmt.Println(lookup("999"))fmt.Println(lookup("0123456"))输出(在Go Playground上尝试):447 0.04958 true447530 0.03 true 0 false0123 0.05 true