The best way to Sq. Each Digit in C++


The problem

You’re requested to sq. each digit of a quantity and concatenate them.

For instance, if we run 9119 by way of the perform, 811181 will come out, as a result of 92 is 81 and 12 is 1.

Notice: The perform accepts an integer and returns an integer

The answer in C++

Possibility 1:

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

Possibility 2:

#embody <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);
}

Possibility 3:

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

Check instances to validate our answer

#embody <random>
#embody <string>

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

  It(Random_tests)
  {
    for(size_t i = 0; i < 100; i++){
      int d = generate_random_num();
      int anticipated = refe(d);
      auto msg = [d]() { return "Incorrect reply for n=" + std::to_string(d); };
      Assert::That(square_digits(d), Equals(anticipated), msg);
    }
  }
  
personal:
  
  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);
  }
};
See also  remedy AttributeError: ‘int’ object has no attribute ‘break up’ – make: [sharedmods] Error 1

Leave a Reply