Tobi Alafin
Tobi Alafin

Reputation: 249

How do I Improve this code

This is the original code.

def d_to_b(dec, bin="")
    dec = dec.to_i
    if (dec < 2)
        bin += dec.to_s
        bin = bin.reverse
        return bin
    else
        a = dec%2
        bin += a.to_s
        d_to_b(dec/2, bin)
    end
end

def b_to_d(bin)
    bin = bin.to_s
    a = (bin.length - 1)
    dec = 0
    i = 0
    while(i <= a)
        dec += (bin[i].to_i)*(2**(a-i))
        i += 1
    end
    return dec
end

I want to improve the code. make it faster, and shorten it. Any help, perhaps a more efficient algorithm.

Upvotes: 0

Views: 80

Answers (1)

Schwern
Schwern

Reputation: 165198

Ruby has built in methods to do base conversions. Fixnum#to_s will take a base to convert to, and String#to_i will take a base to convert from.

$ ruby -e 'puts 12.to_s(2); puts "1100".to_i(2)'
1100
12

Ruby does this work in C, you're not going to do it faster.

If you want to see how Ruby does it, have a look at rb_fix2str() and rb_cstr_parse_inum(). They're not simple.

Upvotes: 4

Related Questions