From 1fb0258c8e6cffb347ad4808690f37bd0a9c4c3d Mon Sep 17 00:00:00 2001 From: Abhinav Anand Date: Sat, 6 Mar 2021 23:38:28 +0530 Subject: [PATCH 1/2] iterative method to convert decimal to binary --- maths/iterative_decimal_to_binary.rb | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 maths/iterative_decimal_to_binary.rb diff --git a/maths/iterative_decimal_to_binary.rb b/maths/iterative_decimal_to_binary.rb new file mode 100644 index 0000000..043f233 --- /dev/null +++ b/maths/iterative_decimal_to_binary.rb @@ -0,0 +1,17 @@ +# Iterative method to convert a given decimal number into binary. + +def decimal_to_binary(n) + bin = [] + until n.zero? + bin << n % 2 + n = n / 2 + end + return bin.reverse.join +end + +puts 'Binary value of 4 is ' + decimal_to_binary(4).to_s +# Binary value of 4 is 100 +puts 'Binary value of 31 is ' + decimal_to_binary(31).to_s +# Binary value of 31 is 11111 +puts 'Binary value of 64 is ' + decimal_to_binary(64).to_s +# Binary value of 64 is 1000000 From 446b0e3085ec40e4c994d5483ae4c4309d12d53a Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 6 Mar 2021 11:48:27 -0800 Subject: [PATCH 2/2] Update iterative_decimal_to_binary.rb --- maths/iterative_decimal_to_binary.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/iterative_decimal_to_binary.rb b/maths/iterative_decimal_to_binary.rb index 043f233..918a7d4 100644 --- a/maths/iterative_decimal_to_binary.rb +++ b/maths/iterative_decimal_to_binary.rb @@ -6,7 +6,7 @@ def decimal_to_binary(n) bin << n % 2 n = n / 2 end - return bin.reverse.join + bin.reverse.join end puts 'Binary value of 4 is ' + decimal_to_binary(4).to_s