Home > database >  While loop misses the first try in R
While loop misses the first try in R

Time:10-22

I want to print reversed binary number of x, but its first digit wouldn't come out. For example, If I put

dbf(35)

results should be

110001

but it comes out as

10001

I think something must be wrong with the while loop, but cannot figure out exactly what.

dbf<-function(x){
  vec<-1:5
  while(x%/%2!=0){
    if(is.integer(x)==F){
      x<-x%/%2
    } else {
      x<-x/2
    }
    vec<-append(vec, x%%2)
  }
  
  vec<-vec[-(1:5)]
  
  cat(vec)
}

CodePudding user response:

The function in the question is complicating too much.

dbf <- function(x){
  vec <- x %% 2
  while(x %/% 2 != 0){
    x <- x %/% 2
    vec <- append(vec, x %% 2)
  }
  vec
}

dbf(35)
#> [1] 1 1 0 0 0 1

sapply(2:6, dbf)
#> [[1]]
#> [1] 0 1
#> 
#> [[2]]
#> [1] 1 1
#> 
#> [[3]]
#> [1] 0 0 1
#> 
#> [[4]]
#> [1] 1 0 1
#> 
#> [[5]]
#> [1] 0 1 1

Created on 2022-10-21 with reprex v2.0.2

  • Related