Last active
August 29, 2015 14:07
-
-
Save FrankWu100/8aa84db9319b850279d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
using namespace std; | |
string itos(int n) | |
{ | |
stringstream ss; | |
ss << n; | |
return ss.str(); | |
} | |
string strAddStr(string str1, string str2) | |
{ | |
if (str1.size() < str2.size()) { | |
string temp = str2; | |
str2 = str1; | |
str1 = temp; | |
} | |
int size1 = str1.size(); | |
int size2 = str2.size(); | |
if (size1 > size2) { | |
for (int i = 0; i < size1 - size2; i++) { | |
str2 = "0" + str2; | |
} | |
} | |
size1 = size2 = str1.size(); | |
int temp = 0, index; | |
string ansStr = ""; | |
for (index = size1-1; index >= 0; index--) { | |
int addedNum = ((int)str1[index]-48) + ((int)str2[index]-48); | |
if (temp != 0) { | |
addedNum = addedNum + temp; | |
temp = 0; | |
} | |
if (addedNum >= 10) { | |
temp = addedNum / 10; | |
int n = addedNum % 10; | |
ansStr = itos(n) + ansStr; | |
} | |
else { | |
ansStr = itos(addedNum) + ansStr; | |
} | |
} | |
if (temp != 0) { | |
ansStr = itos(temp) + ansStr; | |
} | |
return ansStr; | |
} | |
string fib(int n) | |
{ | |
string str1 = "0"; | |
string str2 = "1"; | |
string strAns; | |
if (n == 0 || n == 1) | |
{ | |
return itos(n); | |
} | |
for (int i = 0; i < n-1; i++) { | |
strAns = strAddStr(str1, str2); | |
str1 = str2; | |
str2 = strAns; | |
} | |
return strAns; | |
} | |
int main(int argc, char *argv[]) { | |
int input; | |
cout << "Please input number for N: "; | |
cin >> input; | |
string ans = fib(input); | |
cout << "ANS: " << ans << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment