Software Engineering

How to Square Every Digit in C++


The challenge

You are asked to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.

Note: The function accepts an integer and returns an integer

The solution in C++

Option 1:

int square_digits(int n) {
  int a = 1;
  int m = 0;
  while (n > 0) {
    int d = n % 10;
    m += a * d * d;
    a *= d <= 3 ? 10 : 100;
    n /= 10;
  }
  return m;
}

Option 2:

#include <string>

int square_digits(int num) {
  
  std::string s = std::to_string(num);
  std::string ans;
  for(char c: s){
    int i = c - '0';
    ans += std::to_string(i * i);    
  }
  return std::stoi(ans);
}

Option 3:

int square_digits(int num) {
  
  int total = 0;
  int mul = 1;
  
  while(num) {
    int d = num % 10;
    total += d * d * mul;
    mul *= (d > 3 ? 100 : 10);
    num /= 10;
  }
  
  return total;
}

Test cases to validate our solution

#include <random>
#include <string>

Describe(Square_Every_Digit)
{
      
    It(Sample_tests)
    {       
        Assert::That(square_digits(3212),  Equals(9414),     ExtraMessage("Incorrect answer for n=3212" ));
        Assert::That(square_digits(2112),  Equals(4114),     ExtraMessage("Incorrect answer for n=2112" ));
        Assert::That(square_digits(0),     Equals(0),        ExtraMessage("Incorrect answer for n=0"    ));
        Assert::That(square_digits(13579), Equals(19254981), ExtraMessage("Incorrect answer for n=13579"));
        Assert::That(square_digits(24680), Equals(41636640), ExtraMessage("Incorrect answer for n=24680"));
    } 

  It(Random_tests)
  {
    for(size_t i = 0; i < 100; i++){
      int d = generate_random_num();
      int expected = refe(d);
      auto msg = [d]() { return "Incorrect answer for n=" + std::to_string(d); };
      Assert::That(square_digits(d), Equals(expected), msg);
    }
  }
  
private:
  
  int refe(int d){    
    std::string s = std::to_string(d);
    std::string ans;
    for(char c: s){
      int i = c - '0';
      ans += std::to_string(i * i);    
    }
    return std::stoi(ans);
  }
  
  std::default_random_engine engn { std::random_device{}() }; 
  std::uniform_int_distribution<> d_pick {0, 10000};    
  
  int generate_random_num(){    
    return d_pick(engn);
  }
};