K-th digit in ‘a’ raised to power ‘b’ in C++


In this tutorial, we are going to write a program that finds the k-th digit from the right side in the number ab

It's a straightforward problem. Let's see the steps to solve it.

  • Initialise the numbers a, b, and k.
  • Find the value of abusing pow method.
  • Write a loop that iterates until power value is less than zero or count is less than k.
    • Get the last digit from the power value.
    • Increment the counter.
    • Check whether k and counter are equal or not.
    • Return the digit if they are equal
  • Return -1.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getTheDigit(int a, int b, int k) {
   int power = pow(a, b);
   int count = 0;
   while (power > 0 && count < k) {
      int rem = power % 10;
      count++;
      if (count == k) {
         return rem;
      }
      power /= 10;
   }
   return -1;
}
int main() {
   int a = 5, b = 6;
   int k = 3;
   cout << getTheDigit(a, b, k) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

6

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 09-Apr-2021

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements