c - Google: Divide and return result in form of string -
this question has reply here:
convert fraction string , insert [] repeating part 1 replyi came across interview question asked google , not able find optimized algorithm solve question:
given 2 numbers , b. split , b , homecoming result in form of string.
example 1
input: a=100 , b=3 output: 33.(3) note: (100/3)=33.33333....here 3 in brackets because gets repeated continuously. example 2
input: a=5 , b=10 output: 0.5 example 3
input: a=51 , b=7 output: 7.(285714) note: 51/7 = 7.285714285714285714285714285714......... here 285714 in brackets because repeating. it great if can think of time-optimized algorithm question. give thanks in advance.
you can perform long partition hand, o(n) on number of digits -- it's hard see how improve that.
the problem long partition not terminate ever if fraction repeating decimal, can observe before starting (the fraction repeating decimal iff b has factors other 2 , 5). if repeating decimal, need maintain list of interim remainders have seen. when encounter 1 have seen before, know have found end of repeating period.
c string algorithm division
No comments:
Post a Comment