#include // Write a program that queries the user for an // integer and then counts the number of digits in // that integer. // // The negative sign is not considered a digit. // Thus, // // 5423 has 4 digits, // -5423 has 4 digits, // 8 has 1 digit, // -7 has 1 digit, // // and 0 is considered to have 1 digit. // // Do not convert the integer to a string. // Function declarations int main(); // Function definitions int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; int count{ 0 }; std::cout << "The integer " << n << " has " << count; if ( count == 1 ) { std::cout << " digit."; } else { std::cout << " digits."; } std::cout << std::endl; return 0; } // Hint: // // Make sure you take into account the integer 0, // which is considered to have one digit. // Hint: // // Suppose // // n == 5423. // // What is the result of // // n /= 10; // // after it is executed once? What happens if it is // executed repeatedly? // // Now suppose // // n == 8 // // or // // n == -7. // // What is the result after dividing 'n' by 10 using // integer division? // // Can you repeatedly divide a copy of 'n' by 10 // until it becomes 0, counting how many divisions // were required? // Here is one solution: /* int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; int count{ 0 }; int remaining{ n }; if ( remaining == 0 ) { count = 1; } else { while ( remaining != 0 ) { ++count; remaining /= 10; } } std::cout << "The integer " << n << " has " << count; if ( count == 1 ) { std::cout << " digit."; } else { std::cout << " digits."; } std::cout << std::endl; return 0; } */ // Why does this also work for negative integers? // // In C++, integer division truncates toward zero. // For example, // // 5423 / 10 == 542 // 542 / 10 == 54 // 54 / 10 == 5 // 5 / 10 == 0 // // while // // -5423 / 10 == -542 // -542 / 10 == -54 // -54 / 10 == -5 // -5 / 10 == 0. // // Thus, the same loop counts the digits whether the // integer is positive or negative. There is no need // to change a negative value into a positive value // before counting its digits.