Sample input: "123.456" . Must contain exact 1 dot ('.'). The rest are decimal numbers.
Output: double value of that string.
Solution:
private int GetIntValue(char x) {
return (int)(x - '0');
}
public double ConvertToDouble(string numStr) {
double result = 0;
char[] array = numStr.ToCharArray();
int index = array.Length - 1;
while (index > 0) {
if (array[index] == '.') {
break;
}
result = ( result + GetIntValue(array[index--]) ) * 0.1;
}
index--;
int factor = 1;
while (index >= 0) {
result = result + GetIntValue(array[index--]) * factor;
factor *= 10;
}
Console.WriteLine("result: " + result);
}
Mistakes that I made:
* Typed result += GetIntValue[array[index--] * 0.1 from the first loop.
* Did not decrement index after the first loop.
* On the second loop, I typed while(index > 0) which resulted index 0 was not included on the result.
Comments
Hmm.. kayaknya bs lebih
Hmm.. kayaknya bs lebih simple.. pake string tokenizer.. split by dot "." abis itu array [0] di-casting ke double dan array [1] di-casting ke double tapi dikali 0,1. Resultnya jumlahan dari array[0] dan array[1]
Hmm.. kayaknya bs lebih
Hmm.. kayaknya bs lebih simple.. pake string tokenizer.. split by dot "." abis itu array [0] di-casting ke double dan array [1] di-casting ke double tapi dikali 0,1. Resultnya jumlahan dari array[0] dan array[1]
Hey, that's another one good
Hey, that's another one good article of necessary topic...
Post new comment