标签:cli question include 字典序 pre text 数组 int mod
输入一个待编码的字符串,字符串长度小于等于100.
输出这个编码的index
16331
思路:这道题并没有什么太简便的方法,就是一位一位找到比当前字符串小的字符串个数。
需要注意的就是当右侧没有字符时这个特殊情况,我先后写了两版代码:
第一版:
#include<iostream> #include<string> using namespace std; int main(){ string str; cin>>str; int s = str.size(); if(s == 1){ int res = 0; res += (str[0] - ‘a‘)*25*25*25 + (str[0] - ‘a‘)*25*25 + (str[0] - ‘a‘)*25; res += str[0] - ‘a‘; cout<<res; }else if(s == 2){ int res = 0; res += (str[1] - ‘a‘)*25*25 + (str[1] - ‘a‘)*25; res += str[1] - ‘a‘; res += (str[0] - ‘a‘)*25*25*25 + (str[0] - ‘a‘)*25*25 + (str[0] - ‘a‘)*25; res += str[0] - ‘a‘ + 1; cout<< res; }else if(s == 3){ int res = 0; res += (str[2] - ‘a‘)*25; res += str[2] - ‘a‘; res += (str[1] - ‘a‘)*25*25 + (str[1] - ‘a‘)*25; res += str[1] - ‘a‘ + 1; res += (str[0] - ‘a‘)*25*25*25 + (str[0] - ‘a‘)*25*25 + (str[0] - ‘a‘)*25; res += str[0] - ‘a‘ + 1; cout<< res; }else{ int res = 0; res += str[3] - ‘a‘; res += (str[2] - ‘a‘)*25; res += str[2] - ‘a‘ + 1; res += (str[1] - ‘a‘)*25*25 + (str[1] - ‘a‘)*25; res += str[1] - ‘a‘ + 1; res += (str[0] - ‘a‘)*25*25*25 + (str[0] - ‘a‘)*25*25 + (str[0] - ‘a‘)*25; res += str[0] - ‘a‘ + 1; cout<< res; } return 0; }
第二版:
#include<string> #include<cmath> #include<iostream> #include<vector> using namespace std; int main(){ string str; cin>>str; vector<char> v (str.begin(),str.end()); v.resize(4,‘!‘); int res = 0; for(int i = 0; i < 4 ; ++i){ if(v[i] != ‘!‘){ for(int j = 1; j < 4-i; ++j) res += (v[i] - ‘a‘) *pow(25,j); if(i+1 < 4 && v[i+1] != ‘!‘) res += v[i] - ‘a‘ + 1; else res += v[i] - ‘a‘; } } cout<<res; return 0; }
标签:cli question include 字典序 pre text 数组 int mod
原文地址:https://www.cnblogs.com/J1ac/p/9644050.html