题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
package main import ( "fmt" "math" "sort" ) func num2byte(n int) byte { var bits [4]int idx := 3 for n > 0 { bits[idx] = n % 2 n /= 2 idx-- } for i,j :=0,len(bits)-1; i<j; i,j=i+1,j-1 { bits[i], bits[j] = bits[j], bits[i] } var sum int var powIdx int for i:=len(bits)-1; i>=0; i-- { sum += bits[i] * int(math.Pow(float64(2.0), float64(powIdx))) powIdx++ } if 0 <= sum && sum <= 9 { return byte('0' + sum) } return byte('A' + (sum - 10)) } func byte2byte(ch byte) byte { var num int if '0' <= ch && ch <= '9' { num = int(ch - '0') } if 'A' <= ch && ch <= 'Z' { num = int(ch - 'A') + 10 } if 'a' <= ch && ch <= 'z' { num = int(ch - 'a') + 10 } return num2byte(num) } func transform(s string) string { size := len(s) var even []byte var odd []byte for i:=0; i<size; i++ { if i % 2 == 0 { even = append(even, s[i]) } else { odd = append(odd, s[i]) } } // 分别进行排序 sort.Slice(even, func(i, j int) bool { return even[i] < even[j] }) sort.Slice(odd, func(i, j int) bool { return odd[i] < odd[j] }) sb := make([]byte, size) i, j, idx := 0, 0, 0 for ; i<len(even)&&j<len(odd); i,j=i+1,j+1 { sb[idx] = even[i] sb[idx+1] = odd[j] idx = idx + 2 } if i<len(even) { sb[idx] = even[i] } if j<len(odd) { sb[idx] = odd[j] } // 进制转换 for i:=0; i<size; i++ { if '0' <= sb[i] && sb[i] <= '9' || 'A' <= sb[i] && sb[i] <= 'F' || 'a' <= sb[i] && sb[i] <= 'f' { sb[i] = byte2byte(sb[i]) } } return string(sb) } func main() { var a string var b string fmt.Scan(&a, &b) fmt.Println(transform(a + b)) }
// 本题输入为空格分割的两个字符串,所以采用 fmt.Scan(&a, &b)