Home Software Engineering Methods to Sq. Each Digit in C++

Methods to Sq. Each Digit in C++

0
Methods to Sq. Each Digit in C++

[ad_1]

The problem

You might be requested to sq. each digit of a quantity and concatenate them.

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

Word: 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:

#embrace <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 complete = 0;
  int mul = 1;
  
  whereas(num) {
    int d = num % 10;
    complete += d * d * mul;
    mul *= (d > 3 ? 100 : 10);
    num /= 10;
  }
  
  return complete;
}

Take a look at circumstances to validate our resolution

#embrace <random>
#embrace <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);
    }
  }
  
non-public:
  
  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);
  }
};

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here