任务:32核处理器编号,解析。
- 输入:1,2,3,4-9,11,23-26 字符串形式
- 输出:1,2,3,4,5,6,7,8,9,11,23,24,25,26 到指定整型数组
- 规则:数字从小到大顺序输入,返回处理器核心编号。
cpp Code
//未使用库函数,遍历字符串每个字符,做处理 //有四种情况,一种是单数字,第二种是 '-' 后的数字,第三种是 ',' ,第四种是 '-' #include<iostream> #include<cstdlib> using namespace std; int adaptCoreID(const char* c_str, unsigned int* c_end) { int index = 0; int strIndex = 0; string sl = ""; string sr = ""; bool flag = false; while (c_str[strIndex]) { if ((c_str[strIndex] != ',' && c_str[strIndex] != '-') && flag == false) { sl += c_str[strIndex]; } else if ((c_str[strIndex] != ',' && c_str[strIndex] != '-') && flag == true) { sr += c_str[strIndex]; } else if (c_str[strIndex] == '-') { flag = true; } else if (c_str[strIndex] == ',') { if (sl != "" && sr == "") { unsigned int slInt = std::atoi(sl.c_str()); c_end[index++] = slInt; } else if (sl != "" && sr != "") { unsigned int slInt = std::atoi(sl.c_str()); unsigned int srInt = std::atoi(sr.c_str()); for (unsigned int j = slInt; j <= srInt; j++) { c_end[index++] = j; } } sl = ""; sr = ""; flag = false; } strIndex++; } if (sl != "" && sr == "") { unsigned int slInt = std::atoi(sl.c_str()); c_end[index++] = slInt; } else if (sl != "" && sr != "") { unsigned int slInt = std::atoi(sl.c_str()); unsigned int srInt = std::atoi(sl.c_str()); for (unsigned int j = slInt; j <= srInt; j++) { c_end[index++] = j; } } return index; } int main() { const char *c_str = "2,3-4,6,11-15,17-22,26"; //char *c_str1 = "0"; //char *c_str2 = ""; unsigned int c_endCopy[32]; unsigned int *c_end = c_endCopy; int index = adaptCoreID(c_str, c_end); //测试 for (int i = 0; i < index; i++) { cout << c_end[i] << " "; } system("pause"); return 0; }
Java Code
public class Comba { static int adaptCoreID(final String c_str, int[] c_end) { int index = 0; String[] c_strSplit = c_str.split(","); for (int i = 0; i < c_strSplit.length; i++) { if (!find(c_strSplit[i])) { c_end[index++] = Integer.valueOf(c_strSplit[i]); } else { String[] innerSplit = c_strSplit[i].split("-"); int start = Integer.valueOf(innerSplit[0]); int end = Integer.valueOf(innerSplit[1]); for (int j = start; j <= end; j++) { c_end[index++] = j; } } } return index; } public static boolean find(String s) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '-') { return true; } } return false; } //主函数测试 public static void main(String[] args) { String s = "1,5-9,16,22,23-25"; String s1 = "0"; int[] c_end = new int[32]; int index = adaptCoreID(s, c_end); for (int i = 0; i < index; i++) { System.out.print(" " + c_end[i]); } } }