c – 项目欧拉 – 17
问题是:
我写的代码是: int getCount(map<int,int> numWords,int i) { if (i <= 20) // one to twenty return numWords[i]; else if (i <= 99 && i % 10 == 0) // thirty,forty,fifty etc. return numWords[i]; else if (i <= 99) // thirty one,seventy eight etc. { int md = i % 10; return numWords[i-md] + numWords[md]; // (1) -> if its 55,then take 50; (2) -> take 5 } else if (i <= 999 && i % 100 == 0) // two hundred,five hundred etc. { int md = i / 100; return numWords[md] + numWords[100]; // number + hundred } else if(i <= 999 && i % 10 == 0) // 340 three hundred forty { int hunsDig = (i - (i % 100)) / 100; // (340 - 40)/100 = 3 int tens = i - hunsDig*100; // 340-300=40 return numWords[hunsDig] + numWords[100] + numWords[0] + numWords[tens]; // three hundred and forty } else if(i <= 999) // 342 { int hunsDig = (i - (i % 100)) / 100; // (342 - 42)/100 = 3 int units = i % 10; // 342 % 10 = 2 int tens = (i % 100) - units; // (342 % 100=42) - 2 = 40 int tensCount = tens == 0 ? 0 : numWords[tens]; return numWords[hunsDig] + numWords[100] + numWords[0] + tensCount + numWords[units]; // three hundred and forty two } else if(i==1000) return numWords[1] + numWords[1000]; } void problem17() { // make a map of all the words and corresponding word lengths map<int,int> numWords; numWords[1] = 3; // one numWords[2] = 3; // two numWords[3] = 5; // three numWords[4] = 4; // four numWords[5] = 4; // five numWords[6] = 3; // six numWords[7] = 5; // seven numWords[8] = 5; // eight numWords[9] = 4; // nine numWords[10] = 3; // ten numWords[11] = 6; // eleven numWords[12] = 6; // twelve numWords[13] = 8; // thirteen numWords[14] = 8; // fourteen numWords[15] = 7; // fifteen numWords[16] = 7; // sixteen numWords[17] = 9; // seventeen numWords[18] = 8; // eighteen numWords[19] = 8; // nineteen numWords[20] = 6; // twenty numWords[30] = 6; // thirty numWords[40] = 5; // forty numWords[50] = 5; // fifty numWords[60] = 5; // sixty numWords[70] = 7; // seventy numWords[80] = 6; // eighty numWords[90] = 6; // ninety numWords[100] = 7; // hundred numWords[1000] = 8; // thousand numWords[0] = 3; // and int totalCount = 0; // total num of words for (int i=1; i <= 1000; i++) { totalCount += getCount(numWords,i); } cout << "Total number of letters required: " << totalCount; } 但是,这并没有给我正确的答案.我究竟做错了什么?输出21088,答案是21124. 解决方法
你不是在考虑数十个权利,即111-120 211-220等
int tensCount = 0; if(tens==1) {tenscount = words[10+units]; units=0;} else if(tens>1) {tenscount = words[tens]; units = words[units];} else units = words[units]; 并在退货中添加单位 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |