Keep leading zero in rccp int

Viewed 101

I have a function via Rcpp that reverses an integer

#include <Rcpp.h>
using namespace Rcpp;

//' Reverse an integer
//'
//' @param x A single integer.
//' @export
// [[Rcpp::export]]
int reverse_integer(int x) {
  int reverse = 0;
  while(x != 0){
    int remainder = x%10;
    reverse = reverse*10 + remainder;
    x/=10;
  }
  return reverse;
}

This works fine for numbers without leading or trailing zeroes

reverse_integer(123) == 321

However, when there are zeroes, they will get stripped, i.e.,

reverse_integer(100) == 1

How can I best modify this function so I can still operate on it as an integer, but without losing zeroes?

2 Answers

You need to return a string. 001 is not a different integer than 1 in any programming language. Here's how:

#include <Rcpp.h>
using namespace Rcpp;

//' Reverse an integer
//'
//' @param x A single integer.
//' @export
// [[Rcpp::export]]
std::string reverse_integer(int x) {
  int reverse = 0;
  int ndigits = 0;
  while(x != 0){
    int remainder = x%10;
    reverse = reverse*10 + remainder;
    x/=10;
    ndigits++;
  }
  std::string output(ndigits, '\0');
  char * outputp = &output[0];
  std::string fmt_string = "%0" + std::to_string(ndigits) + "d";
  sprintf(outputp, fmt_string.c_str(), reverse);
  return output;
}

Example:

reverse_integer(103400)
[1] "004301"

By default the number formatter will not print any leading zeroes.

You will need to return a string instead of an int if you want to preserve leading zeroes. You change your function to count the number of trailing zeroes in the input, and prepend them to the returned string.

Related