recursion - Integer to Binary in scala -
just kicks decided write snippet takes integer , converts binary. seems performing conversion wondering if there's might missing this. great feedback.
thanks
def converttobinary(n: int, bin: list[int]): string = { if(n/2 == 1) { (1::(n%2)::bin).mkstring(" ") } else { val r = n%2;val q = n/2;converttobinary(q,r::bin) } }
1) formatting :-)
def converttobinary(n:int, bin:list[int]):string = { if(n/2 == 1) (1:: (n % 2) :: bin).mkstring(" ") else { val r = n % 2; val q = n / 2; converttobinary(q, r::bin) } }
2) signature:
i omit convert part, made accumulator optional parameter (function user doesn't have supply arguments used internal implementation, right?)
def tobinary(n:int, bin: list[int] = list.empty[int]): string = { if(n/2 == 1) (1:: (n % 2) :: bin).mkstring(" ") else { val r = n % 2 val q = n / 2 tobinary(q, r::bin) } }
now can used as:
val str = tobinary(42)
somebody might propose pimp such function, call might
val str = 42.tobinary // btw, there such function in std lib: 42.tobinarystring
but don't see profit.
the other thing bothers me you're using list & mkstring purpose, why not stringbuilder? q , r?
and final minor point -- place @annotation.tailrec
ensure function optimized in case of future changes
Comments
Post a Comment