classSolution { public: inttitleToNumber(string s){ int length = s.size(); longlong result = 0; for(int i = 0; i<length; i++) { result = result*s的进制数 + s[i]的数字形式;; } return result; } };
比如26进制转10进制
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: inttitleToNumber(string s){ int length = s.size(); longlong result = 0; for(int i = 0; i<length; i++) { //【s[i]-'A'+1】将A、B、C... 映射到 1、2、3... result = result*26 + s[i]-'A'+1; } return result; } };
再比如2进制转10进制
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: inttitleToNumber(string s){ int length = s.size(); longlong result = 0; for(int i = 0; i<length; i++) { //【s[i]-'0'】将字符'0'、'1'、'2'...映射到数字1、2、3.... result = result*2 + s[i]-'0'; } return result; } };
1.2 十进制转任意进制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
charget(int x)//将x转换为字符形式 { if (x <= 9) return x + '0'; return x - 10 + 'A'; }
string change_base(int n, int b)//【短除法】将十进制整数n转换为b进制,返回对应字符串 { string res; while (n) { res += get(n % b); n /= b; } reverse(res.begin(), res.end());//翻转回高位在左 return res; }
/*both a and b are in reversed order*/ vector<int> add(vector<int>& a, vector<int>& b) { vector<int> re; int t = 0; //accumulator for (int i = 0; i < a.size() || i < b.size(); i++) { if (i < a.size()) t += a[i]; if (i < b.size()) t += b[i]; re.push_back(t % 10); t /= 10; //if t>10, t/10 = 1 } if (t) re.push_back(1); //t产生进位 return re; }
/*1. both a and b are in reversed order 2. a is bigger than b */ vector<int> subtract(vector<int>& a, vector<int>& b) { vector<int> re; int t = 0; //accumulator for (int i = 0; i < a.size(); i++) { t = a[i]-t; if (i < b.size()) t -= b[i]; re.push_back((t + 10) % 10);//if t<0, t+=10 if (t < 0) t = 1; //如果t<0, 下一次计算a[i]要被减去1(借位) else t = 0; } /*消除前导零/ while (re.size() > 1 && re.back() == 0) re.pop_back(); return re; }
vector<int> mul(vector<int>& arr, int b) { vector<int> re; int t = 0; for (int i = 0; i <arr.size()||t; i++) //“||t”表示如果进位没处理完,则循环还要继续 { if( i<arr.size() ) t = arr[i] * b + t; re.push_back(t % 10); t /= 10; } return re; }
#include<iostream> #include<algorithm> usingnamespace std; constint N = 100010; int q[N];
intmain(){ int n; cin>>n; for(int i = 0;i<n;i++) cin>>q[i]; sort(q, q+n); //当n为偶数时x取到中间两个点的中间,为奇数时x直接取到最中间那个点上 int x = n%2==0?q[n/2]+q[n/2-1]>>1:q[n/2]; int re = 0; for(int i = 0;i<n;i++) re += abs(q[i]-x); cout<<re<<endl; return0; }