How to get the first x leftmost digits of an integer number in C++

2 Answers

0 votes
#include <iostream>
#include <ctime>
#include <cmath>
  
int x_leftmost_digit(int n, int x);
  
int main() {
    int n, x;
  
    std::srand(std::time(nullptr));
  
    for (int i = 1; i <= 5; i++) {
        n = std::rand() % 100000 + 1;
        x = std::rand() % 5 + 1; // note the x can be 4 leftmost digits and n 3 digit number...
        std::cout << x << " leftmost digit of " << n << " is " << x_leftmost_digit(n, x) << "\n";
    }
}
  
int x_leftmost_digit(int n, int x) {
    x = std::pow(10, x);
    while (n > x) {
        n = n / 10;
    }
  
    return n;
}
  
     
     
/*
run:
        
4 leftmost digit of 74169 is 7416
5 leftmost digit of 93068 is 93068
3 leftmost digit of 9905 is 990
3 leftmost digit of 11512 is 115
1 leftmost digit of 59083 is 5
                 
*/

 



answered Dec 7, 2024 by avibootz
edited Dec 8, 2024 by avibootz
0 votes
#include <iostream>
#include <string>
#include <ctime>

int x_leftmost_digit(int n, int x) {
    
    // Convert the number to a string
    std::string numberStr = std::to_string(n);

    // Extract the first x digits
    std::string leftmostDigits = numberStr.substr(0, x);

    // Convert the result back to an integer if needed
    return std::stoi(leftmostDigits);
}

int main() {
    std::srand(std::time(nullptr));

    for (int i = 1; i <= 5; i++) {
        int n = std::rand() % 100000 + 1;
        int x = std::rand() % 5 + 1; // note the x can be 4 leftmost digits and n 3 digit number...

        std::cout << x << " leftmost digit of " << n << " is " << x_leftmost_digit(n, x) << "\n";
    }
}


   
   
/*
run:
      
3 leftmost digit of 40826 is 408
1 leftmost digit of 26067 is 2
2 leftmost digit of 96229 is 96
4 leftmost digit of 37366 is 3736
5 leftmost digit of 7460 is 7460

*/

 



answered Dec 7, 2024 by avibootz
edited Dec 8, 2024 by avibootz

Related questions

1 answer 1,177 views
1 answer 132 views
1 answer 134 views
1 answer 122 views
1 answer 130 views
...