N 进制

1、指定一串字符串表示进制数,求给定字符串在该进制下的的下一位

package main

import (
    "fmt"
)

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 给定数值的下一个数值
 * @param chars string字符串一维数组 构成N进制的n个字符
 * @param currentValue string字符串 当前值
 * @return string字符串
 */
func nextValue( chars []string ,  currentValue string ) string {
    // write code here
    ht := map[rune]rune{'零':'0','壹':'1','贰':'2','叁':'3','肆':'4','伍':'5','陆':'6','柒':'7',
        '捌':'8','玖':'9'}
    ht1 := map[rune]string{'0':"零",'1':"壹",'2':"贰",'3':"叁",'4':"肆",'5':"伍",'6':"陆",'7':"柒",
        '8':"捌",'9':"玖"}
    // 因为传递的参数多样化(可中可英),所以统一转化为 rune 处理
    currentV := []rune(currentValue)
    tmp := []rune{}
    f := false
    if currentV[0] >= '0' && currentValue[0] <= '9' {
        for i := len(currentV)-1; i >= 0; i-- {
            tmp = append(tmp, currentV[i])
        }
    } else {
        f = true
        for i := len(currentV)-1; i >= 0; i-- {
            cv, _ := ht[currentV[i]]
            tmp = append(tmp, cv)
        }
    }
    //fmt.Println(reflect.TypeOf('0'))   rune/int32
    add := 1
    for i := 0; i < len(tmp); i++ {
        if int(tmp[i]-'0')+add == len(chars) {
            tmp[i] = '0'
            add = 1
        } else {
            tmp[i] = tmp[i]+1 // ❤
            add = 0 // 重置
            break
        }
    }
    ans := ""
    if add == 1 {
        cur := "1"
        if f {
            cur = ht1['1']
        }
        ans += cur

    }
    for i := len(tmp)-1; i >= 0; i-- {
        cur := string(tmp[i])
        if f {
            cur = ht1[tmp[i]]
        }
        ans += cur
    }
    return ans
}

func main() {
    //chars := []string{"零","壹","贰","叁","肆","伍","陆","柒","捌"} // "玖"
    //currentValue := "壹捌捌"
    chars := []string{"0","1","2","3","4","5","6","7","8"} // "9"
    currentValue := "8888"
    fmt.Println(nextValue(chars, currentValue))
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务