By: Saurav
2017-12-27 03:17:00 UTC
This question is from cracking the coding interview moderate problems:
Write a function to swap a number in place (that is without temporary variables)
let's start by writing some tests first:
p invert_number_inplace(427723) == 327724 p invert_number_inplace(723) == 327 p invert_number_inplace(4) == 4 invert_number_inplace(-400001) == -100004
def invert_number_inplace(n) return n if 0 < n and n < 10 n_str = n.abs.to_s size = n_str.size (0..((size/2)-1)).each do |i| swap(n_str,i,(size-i-1)) end n < 0 ? "-#{n_str}".to_i : n_str.to_i end def swap(str,i,j) str[i] = (str[i].to_i ^ str[j].to_i).to_s str[j] = (str[i].to_i ^ str[j].to_i).to_s str[i] = (str[i].to_i ^ str[j].to_i).to_s end invert_number_inplace(-400001)
Lets clean this a little bit
def invert_number_inplace(n) return n if 0 < n and n < 10 n_str = n.abs.to_s size = n_str.size n_str = perform_swapping(size,n_str) n < 0 ? "-#{n_str}".to_i : n_str.to_i end def perform_swapping(size,n_str) (0..((size/2)-1)).each do |i| swap(n_str,i,(size-i-1)) end return n_str end def swap(str,i,j) str[i] = (str[i].to_i ^ str[j].to_i).to_s str[j] = (str[i].to_i ^ str[j].to_i).to_s str[i] = (str[i].to_i ^ str[j].to_i).to_s end
Owned & Maintained by Saurav Prakash
If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)