Microsoft Interview Question
Software Engineer / DevelopersOnly 1 problem in BackBencher's solution:
Lets say ur input number = 10.23456
once u r @ 10234.56 and multiply with 10, the next number comes as 102345.5999999998 instead 102345.6
so the loop will go on, never complete...
and thts the behavior of double and float.
best way to do is convert to string and do it.
any comment?
how abt this?
say n=1.25
the ans is:
x=(n-(int)n)*10
and now (int)x will be the ans..
correct if i am wrong
you dint seem to understand problem using real numbers here.. I think best way is to convert the given number to string and then proceed with
int count=0,buffer=0;
while(num[i]!='\n'){
if(num[i]=='0'){
buffer++;
}else{
buffer++;
count = buffer;
buffer=0;
}
}
correct me if im wrong
your code works.
I am pasting the same code with no errors. Just one thing, we have to convert a decimal number to its char * form.
int main(){
...int count=0,buffer=0;
...char* num ="1234.00001\n";
...int i =0;
...while(num[i]!='\n'){
......if(num[i]=='0'){
.........buffer++;
......}else{
.........buffer++;
.........count = buffer;
.........buffer=0;
......}
......i++;
...}
...cout <<"\n Count of decimals: " << count << endl;
...return 0;
}
#include<iostream>
#define str(x) #x
using namespace std;
int main()
{
int count=0;
int count2=0;
bool count2Flag = false;
char* s=str(3.45000);
while(*s++)
{
if(*s == '.')
{
s++;
while(*s)
{
cout<<s<<endl;
if(*s == '0')
{
count2++;
count2Flag=true;
}
else
{
if(count2Flag)
{
count+=count2;
count2=0;
count2Flag=false;
}
count++;
}
s++;
}
break;
}
}
cout<<count;
return 0;
}
modulo operator does not work on floats or double (atleast in C++)...but with similar concept you can implement doing something like below. Although it has issues about float type...you just can't trust the behaviour... 3.123 can become 3.12999999998 etc...and you will end up in infinite loop..
EG.
while(num != 0)
{
num = num - (int)num;
count++;
num *= 10;
}
string to_string(float f)
{
stringstream str;string s;str<<f;str>>s;return s;
}
int no_of_zero(string s)
{
int i=0,l=s.length();bool dotpresent=false;
while(i<l && s[i]!='.'){i++;if(s[i]=='.')dotpresent=true;}
if(!dotpresent)return 0;
while(s[--l]=='0');
return l-i;
}
int main()
{
float f;cin>>f;//no to b converted
cout<<no_of_zero(to_string(f))<<endl;
system("pause");
return 0;
}
note that we can take any floating point no directly as input string...
In this case to_string will be redundant...
this works for the trailing zeroes case
- suatman December 01, 2008#include<iostream>
#define str(x) #x
using namespace std;
int main()
{
int count=0;
char* s=str(3.45000);
while(*s++)
{
if(*s++=='.')
{ while(*s++)
{
count++;
}
}
}
cout<<count;
return 0;
}