Convert from char to int OR Convert from int to char
2013-08-06 10:14
232 查看
//This is a feasible answer for '1_SRM_144DIV1-300' on topCoder. class BinaryCode{ public: vector<string> decode(string message) { int len = message.size(); vector<string> vec; if(len == 0){ cout << "No data" << endl; return vec; } string zeroBg = convert(message,'0'); //assume the original binary code begin with '0' string oneBg = convert(message,'1'); //assume the original binary code begin with '1' vec.push_back(zeroBg); vec.push_back(oneBg); return vec; } private: string convert(const string& message,char guess){ int len = message.size(); string d_str(len,'0');//allocate len size space for d_str ,which is used to store original binary code d_str[0] = guess; for(string::size_type i = 1; i < len; ++i){ if(i == 1) //将char类型转换为int类型,调用自定义的函数cToi,从整形转换为字符类型可使用在char类型的'0'的基础上加一整形实现。 //例如:将int型的2转换为字符型的'2',可采用'0' + 2,或者将char型的'2'转换为int型的2,可采用'2' - '0'; d_str[i] += cToi(message[i - 1]) - cToi(d_str[i - 1]); else d_str[i] += cToi(message[i - 1]) - cToi(d_str[i - 1])- cToi(d_str[i - 2]); if(cToi(d_str[i]) >= 2){ d_str = "NONE"; break; } } if(d_str != "NONE") if( (len == 1 && message[0] != d_str[0]) || (cToi(message[len - 1]) != cToi(d_str[len - 1]) + cToi(d_str[len - 2])) ) d_str = "NONE"; return d_str; } size_t cToi(char ch){ return ch - '0'; } }
相关文章推荐
- 概率最大骰子总和 Topcoder SRM 536 DIV1 第2题
- TopCoder SRM 569 DIV2 Level3: MegaFactorialDiv2
- Topcoder SRM Div2 Level2
- Topcoder SRM 547 DIV1 Level 1: Pillars
- TopCoder SRM DIV2 Level 3: RelativelyPrimeSubset
- TopCoder SRM 558 DIV2 Level 3:CatAndRabbit
- Topcoder/SRM565
- TOPCODER/SRM565 DIVII 250、500pt(500pt无递归解法)
- TOPCODER/SRM 566 DIVII(250、500、1000题)(1000PT暂未附上代码)
- TOPCODE/SRM567 DIVII 250、500PT
- TopCoder: SmartWordToy BFS算法
- TopCoder: CaptureThemAll BFS算法
- TopCoder: RevolvingDoors BFS算法
- TopCoder: WalkingHome BFS算法
- TopCoder入门教程 -- sqybi完善版
- SRM 582 Div II Level Two SpaceWarDiv2
- TopCoder 入门 顺便认识sqybi大牛
- 3月6日TopCoder上250分和500分的代码(我自己写的)
- TopCoder一简单题的解题过程
- topcoder SRM 625 DIV2 A