3-Liner
小朋友好久以前貼在夢想家 Programming 板上的題目:
作者 aoc90058 (up ! up! up!) 站內 Programming
標題 小小的題目
時間 2005/11/25 Fri 01:52:49
系統將給你一個檔案,請將此TXT檔案中,
所出現的數字總合輸出。
input sample
98+458 48s7ds5 da1daf845
asdf8asdf48 sd54adf8 548d5
.sdaf5484//faf51 48a
output sample
7716
#include<fstream>
#include<iostream>
#include<algorithm>
#include<functional>
#include<iterator>
#include<numeric>
#include<sstream>
using namespace std;
int main(){
ifstream fin("p.txt");
string temp;
unsigned int sum=0;
while(getline(fin,temp)){
replace_if(temp.begin(),temp.end(),not1(ptr_fun(isdigit)),' ');
sum+=accumulate(istream_iterator<unsigned int> (istringstream
(temp)),istream_iterator<unsigned int> (),0);
}
cout<<sum<<endl;
system("PAUSE");
}
//好玩的地方在於,幾乎以STL解決,整個感覺相當舒暢。
--
╭┼ Origin: 彰化高中˙華陽夢想家 dreamer.chsh.chc.edu.tw
┼┘ Author: aoc90058 從 220-134-89-111.HINET-IP.hinet.net 發表
啊,那 STL 技巧的確不錯,但遇上 Ruby 也得甘拜下風 ─ Ruby 只要三行:
1: sum = 0
2: gets(nil).scan(/\d+/) {|s| sum += s.to_i}
3: puts sum
今天真是嚴重失眠。
--
小朋友的 ID 後面…原來確有此事啊。
或是寫成這樣,可能比較熟悉,只是多了一行:
1: require 'scanf'
2: sum = 0
3: gets(nil).scanf("%d%[^0-9]") {|i| sum += i}
4: puts sum
不過還是 regular expression 比較好看吧 :)。
--
關於字串處理,要和 script languages(e.g. Ruby, Python, Perl)拚,必敗無疑。
再變形 ─ 若出現負數亦得處理。Sample Input:s985-86lkd-23;Sample Output:876。
1: sum = 0
2: gets(nil).scan(/-?\d+/) {|s| sum += s.to_i}
3: puts sum
Ruby 加兩個字元進去就行了,C++ 麻煩一點。另外,小朋友的 C++ 程式有個漏洞。Sample Input:1234567890987654321;Sample Output:1234567890987654321。
--
XD


很好,兩個都看不太懂...繼續努力去
話說才剛把世紀末看完,回頭繼續看STL...
這...這個漏洞...你要用long long 嗎..XD
那再加個幾百位好了 :P。
如果再加上大數運算,那就有些折磨那時的學
弟了(一年級),不過如果真的要那麼做,好
像就必須要自訂型別了,否則STL也搭不上
吧!頗麻煩的呢!
結論就是:我想偷懶。
<< 回到主頁