Little useless-useful R functions – Reverse integer

[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Reverse integer is another interview question, that allegedly could be asked by the interviewer. Original question or problem is posted at the Leetcode.

The problem is described as:

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 – 1], then return 0.

For example:

x = 120; reversed_x = 21
x = -2310; reversed_x = -132

Useless function kind of looks cool.

reverseInteger <- function(x){
  if ( -2**31 < x & x > 2**31 -1) return(0) #must be inside the integer boundaries
  if (x < 0) { 
    x2 <- x*-1
    r_ints <- (rev(strsplit(as.character(x2), "")[[1]]))
  } else {
    r_ints <- (rev(strsplit(as.character(x), "")[[1]]))
  }
  r_ints2 <- paste(r_ints, collapse = "")
  r_ints2 <- as.numeric(r_ints2)
  
  return(r_ints2)
}

And we run the some normal numbers to test the validity:

reverseInteger(-4122310)
# [1] -132214
reverseInteger(122310)
# [1] 13221
reverseInteger(12223456789)
# [1] 0

So it looks. Right, all good. What if we take the edge case of 2147483647 (which is 2^31-1). When we reverse the number, we get 7463847412, making the solution fall out of the boundaries of an integer with the size of 2^31, even though the original number still falls within the boundaries.

In this case, we add additional checker:

reverseInteger <- function(x){
  if ( -2**31 < x & x > 2**31 -1) return(0) #must be inside the integer boundaries
  if (x < 0) { 
    x2 <- x*-1
    r_ints <- (rev(strsplit(as.character(x2), "")[[1]]))
  } else {
    r_ints <- (rev(strsplit(as.character(x), "")[[1]]))
  }
  r_ints2 <- paste(r_ints, collapse = "")
  r_ints2 <- as.numeric(r_ints2)
  

  if ( -2**31 < r_ints2 & r_ints2 > 2**31 -1) {
      return(0) 
  } else {
  return(r_ints2)
 }
}
}

And now we can test the function against the bigger number:

reverseInteger(2147483646)
# [1] 0

As always, code is available on Github in  Useless_R_function repository. The sample file in this repository is called: ReverseInteger.R. Check the repository for future updates.

Happy R-coding and stay healthy!

To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)