Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a number at a particular digit in a number [closed]

I want to get number present at the specific index.

Suppose the number is "123456789" and i need to return the number at position 3 from left.

Should I convert this number to a string and re-convert the char at specific index to integer to get the number value?

Is there any inbuilt function to do so in C++?

like image 253
Underoos Avatar asked Jul 24 '15 14:07

Underoos


3 Answers

To get the digit at any place in the number than you can use a simple string conversion:

int foo = 123456789;
int pos = 3;
// convert to string and use the [] operator
std::cout << std::to_string(foo)[pos - 1];//need to subtract 1 as C++ is 0 index based
like image 145
NathanOliver Avatar answered Oct 16 '22 05:10

NathanOliver


This should return the third digit that of a number!

cout << "Enter an integer";
int number;
cin >> number;
int n = number / 100 % 10

Or (for all digits):

 int number = 12345;
 int numSize = 5;
for (int i=numSize-1; i>=0; i--) {
  int y = pow(10, i);
  int z = number/y;
  int x2 = number / (y * 10);
  printf("%d-",z - x2*10 );
}
like image 1
Kurt Avatar answered Oct 16 '22 05:10

Kurt


The use of std::stringstream

std::string showMSD3(int foo)
{
   std::stringstream ssOut;

   std::string sign;
   std::stringstream ss1;
   if(foo < 0) {
      ss1 << (-1 * foo);
      sign = '-';
   }
   else
      ss1 << foo;

   std::string s = ss1.str();

   ssOut << "               foo string: '"
         << sign << s << "'" << std::endl;

   if(s.size() > 2)
   {
      ssOut << " Most Significant Digit 3: "
            << s[2] // 1st digit at offsset 0
            << "\n            has hex value: 0x"
            << std::setw(2) << std::setfill('0') << std::hex
            << (s[2] - '0')
            << std::endl;
   }
   else
      ssOut << "                      Err: foo has only "
            << s.size() << " digits" << std::endl;

   return (ssOut.str());
}

and somewhere closer to main (perhaps in main):

   // test 1
   {
      std::cout << showMSD3(123456789) << std::endl;
   }

   // test 2
   {
      std::cout << showMSD3(12) << std::endl;
   }

   // test 3 - handle negative integer
   {
      std::cout << showMSD3(-123) << std::endl;
   }

with output

               foo string: '123456789'
 Most Significant Digit 3: 3
            has hex value: 0x03

               foo string: '12'
                      Err: foo has only 2 digits

               foo string: '-123'
 Most Significant Digit 3: 3
            has hex value: 0x03
like image 1
2785528 Avatar answered Oct 16 '22 06:10

2785528