r/ProgrammingPrompts • u/Kxaos • Aug 26 '15
Write a pure toString() && toInteger()
Write your own toString(int number) and toInteger(string str) functions. you can't "include" or "import" or "using" anything. you can't use built-in functions Make them 100% pure ;) Good Luck!
My solution: ( C++ )
// Get the length of an integer
int length(int data,int len=0){return(!(data/10)?++len:length(data/10,++len));}
string toString(int num){
string str="";int temp;
for(int i=0;i<length(num);i++){
temp=num;for(int j=i;j<length(num)-1;j++)temp/=10;
str+=length(temp)>1?(temp-((temp/10)*10))+48:temp+48;}
return str;}
int toInteger(string str){
int total=0,temp=0;
for(int i=0;i<str.length();i++){
temp=str[i]>='0'&&str[i]<='9'?str[i]-48:0;
for(int j=i;j<str.length()-1;j++)temp*=10;
total+=temp;}
return total;}
6
Upvotes
View all comments
Show parent comment
1
u/ultimamax Aug 28 '15
Well the trouble is if I used some lang like C I'd be able to cast integers to chars and vice versa to get the same effect as ord() or chr(), but python doesn't allow that without using these functions I believe.
If I hadn't used them, my solution would be pretty boring I think. I would probably use dicts to switch digits and their character equivalents.