Printing the digits of a number from left to right linewise - c++

The Problem Statement is:
You've to display the digits of a number.
Take as input "n", the number for which digits have to be displayed.
Print the digits of the number line-wise.
#include<iostream>
#include<cmath>
using namespace std;
int main(){
int n;
cin>>n;
int nod = 0;
int temp = n;
while(temp != 0){
temp = temp / 10;
nod++;
}
int div = (int)pow(10, nod - 1);
while(div != 0){
int dig = n / div;
cout<<dig<<endl;
n = n % div;
div = div / 10;
}
return 0;
}
For input 65784383, the expected output is:
6
5
7
8
4
3
8
3
However the ouput from the program is not as expected. Where did it go wrong?

Maybe you get wrong output, I don't know, you didn't say why you think there is something wrong with the code.
I do get correct output here: https://godbolt.org/z/xsTxfbxEx
However, this is not correct:
int div = (int)pow(10, nod - 1);
pow is not for integers. I suggest you to read documentation and this, and consider what happens when you truncate a floating point number to an integer.
To print linewise digits of a number given by the user all you need is this:
#include <iostream>
#include <string>
int main() {
std::string input;
std::cin >> input;
for (const auto& c : input) std::cout << c << "\n";
}
Maybe you consider this cheating and insist on doing the maths. Then collect the digits from back to front and print in reverse order, thats much simpler:
#include <iostream>
#include <vector>
int main() {
int n;
std::cin >> n;
std::vector<int> digits;
while (n) {
digits.push_back(n % 10);
n /= 10;
}
for (auto it = digits.rbegin(); it != digits.rend(); ++it){
std::cout << *it << "\n";
}
}
PS: Do not use c-style casts like you do here
int div = (int)pow(10, nod - 1);
//^^
Actually it is superfluous here, because assigning a floating point number to an int already does the truncation. Though, also in general c-style casts are to be avoided. As far as I know, the only reason they are allowed is backwards compatibility. If you do need to cast you should use static_cast. Most of the time c-style casts merely silence compiler warnings or errors and hide problems in the code.

Related

Unable to have 100 factorial with C++ on output screen(displaying 0)

Well I am stuck on this problem for quite a while:
Question:
You are asked to calculate factorials of some small positive integers.
Input:
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output:
For each integer n given at input, display a line with the value of n!
//coded in c++
#include <bits/stdc++.h> //loadind up all the libraries at once.
using namespace std;
int main()
{ int T;
scanf("%d", &T);
//I am not doing "cin<<" cause "scanf" is faster than it
for (int i = 0; i < T; i++)
{
int N;
scanf("%d",&N);
long long int product = 1;
while (N >0){
product = product * N;
N--;
}
printf("%lld\n",product);
}
return 0;
}
I am able to get 10!,20! but unable to get 100! (factorial)
so the extreme case doesn't satisfy. Please help me to get a good data type for my variable as 100! a factorial has over than 100 digits. It is displaying 0 when I input 100 on the terminal.
P.S - This problem is from CodeChef website (FCTRL2).
A 64bit integer will overflow with 23!
Therefore you need to do it with digits and a vector.
This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 23!.
The answer will be exact.
With such an approach the calculation is simple. I do not even know what to explain further.
Please see the code:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Calculate n! Enter n (max 10000): ";
if (unsigned int input{}; (std::cin >> input) && (input <= 10000)) {
// Here we store the resulting number as single digits
std::vector<unsigned int> result(3000, 0); // Magic number. Is big enough for 100000!
result.back() = 1; // Start calculation with 1 (from right to left)
// Multiply up to the given input value
for (unsigned int count = 2; count <= input; count++)
{
unsigned int sum{}, remainder{};
unsigned int i = result.size() - 1; // Calculate from right to left
while (i > 0)
{
// Simple multiplication like on a piece of paper
sum = result[i] * count + remainder;
result[i--] = sum % 10;
remainder = sum / 10;
}
}
// Show output. Supporess leading zeroes
bool showZeros{ false };
for (const unsigned int i : result) {
if ((i != 0) || showZeros) {
std::cout << i;
showZeros = true;
}
}
}
else std::cerr << "\nError: Wrong input.";
}
Using a bigint library will be much faster.
Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.
Additionally compiled and tested with clang11.0 and gcc10.2
Language: C++17

Comparing digits in number

Consistently comparing digits symmetrically to its middle digit. If first number is bigger than the last , first is wining and I have to display it else I display last and that keep until I reach middle digit(this is if I have odd number of digits), if digit don't have anything to be compared with it wins automatically.
For example number is 13257 the answer is 7 5 2.
Another one 583241 the answer is 5 8 3.
For now I am only trying to catch when number of digits is odd. And got stuck.. This is my code. The problem is that this code don't display any numbers, but it compares them in the if statement(I checked while debugging).
#include <iostream>
using namespace std;
int countDigit(int n) {
int count = 0;
while (n != 0) {
count++;
n /= 10;
}
return count;
}
int main() {
int n;
cin >> n;
int middle;
int count = countDigit(n);
if (count % 2 == 0) {
cout<<"No mid digit exsist!!";
}
else {
int lastDigit = n % 10;
middle = (count + 1) / 2;
for (int i = 0; i < middle; i++) {
for (int j = lastDigit; j<middle; j--) {
if (i > j) {
cout << i <<' ';
}
else {
cout << j;
}
}
}
}
return 0;
}
An easier approach towards this, in my opinion, would be using strings. You can check the size of the string. If there are even number of characters, you can just compare the first half characters, with the last half. If there are odd numbers, then do the same just print the middle character.
Here's what I'd do for odd number of digits:
string n;
cin>>n;
int i,j;
for(i=0,j=n.size()-1;i<n.size()/2,j>=(n.size()+1)/2;i++,j--)
{
if(n[i]>n[j]) cout<<n[i]<<" ";
else cout<<n[j]<<" ";
}
cout<<n[n.size()/2]<<endl;
We analyze the requirements and then come up with a design.
If we have a number, consisting of digits, we want to compare "left" values with "right" values. So, start somehow at the left and the right index of digits in a number.
Look at this number: 123456789
Index: 012345678
Length: 9
in C and C++ indices start with 0.
So, what will we do?
Compare index 0 with index 8
Compare index 1 with index 7
Compare index 2 with index 6
Compare index 3 with index 5
Compare index 4 with index 4
So, the index from the left is running up and the index from the right is running down.
We continue as long as the left index is less than or equal the right index. All this can be done in a for or while loop.
It does not matter, wether the number of digits is odd or even.
Of course we also do need functions that return the length of a number and a digit of the number at a given position. But I see that you know already how to write these functions. So, I will not explain it further here.
I show you 3 different examples.
Ultra simple and very verbose. Very inefficient, because we do not have arrays.
Still simple, but more compressed. Very inefficient, because we do not have arrays.
C++ solution, not allowed in your case
Verbose
#include <iostream>
// Get the length of a number
unsigned int length(unsigned long long number) {
unsigned int length = 0;
while (number != 0) {
number /= 10;
++length;
}
return length;
}
// Get a digit at a given index of a number
unsigned int digitAt(unsigned int index, unsigned long long number) {
index = length(number) - index - 1;
unsigned int result = 0;
unsigned int count = 0;
while ((number != 0) && (count <= index)) {
result = number % 10;
number /= 10;
++count;
}
return result;
}
// Test
int main() {
unsigned long long number;
if (std::cin >> number) {
unsigned int indexLeft = 0;
unsigned int indexRight = length(number) - 1;
while (indexLeft <= indexRight) {
if (digitAt(indexLeft, number) > digitAt(indexRight, number)) {
std::cout << digitAt(indexLeft, number);
}
else {
std::cout << digitAt(indexRight, number);
}
++indexLeft;
--indexRight;
}
}
}
Compressed
#include <iostream>
// Get the length of a number
size_t length(unsigned long long number) {
size_t length{};
for (; number; number /= 10) ++length;
return length;
}
// Get a digit at a given index of a number
unsigned int digitAt(size_t index, unsigned long long number) {
index = length(number) - index - 1;
unsigned int result{}, count{};
for (; number and count <= index; ++count, number /= 10)
result = number % 10;
return result;
}
// Test
int main() {
if (unsigned long long number; std::cin >> number) {
// Iterate from left and right at the same time
for (size_t indexLeft{}, indexRight{ length(number) - 1 }; indexLeft <= indexRight; ++indexLeft, --indexRight)
std::cout << ((digitAt(indexLeft,number) > digitAt(indexRight, number)) ? digitAt(indexLeft, number) : digitAt(indexRight, number));
}
}
More modern C++
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
if (std::string numberAsString{}; std::getline(std::cin, numberAsString) and not numberAsString.empty() and
std::all_of(numberAsString.begin(), numberAsString.end(), std::isdigit)) {
for (size_t indexLeft{}, indexRight{ numberAsString.length() - 1 }; indexLeft <= indexRight; ++indexLeft, --indexRight)
std::cout << ((numberAsString[indexLeft] > numberAsString[indexRight]) ? numberAsString[indexLeft] : numberAsString[indexRight]);
}
}
You are trying to do something confusing with nested for-cycles. This is obviously wrong, because there is nothing “quadratic” (with respect to the number of digits) in the entire task. Also, your code doesn’t seem to contain anything that would determine the highest-order digit.
I would suggest that you start with something very simple: string’ify the number and then iterate over the digits in the string. This is obviously neither elegant nor particularly fast, but it will be a working solution to start with and you can improve it later.
BTW, the sooner you get out of the bad habit of using namespace std; the better. It is an antipattern, please avoid it.
Side note: There is no need to treat odd and even numbers of digits differently. Just let the algorithm compare the middle digit (if it exists) against itself and select it; no big deal. It is a tiny efficiency drawback in exchange for a big code simplicity benefit.
#include <cstdint>
#include <iostream>
#include <string>
using std::size_t;
using std::uint64_t;
uint64_t extract_digits(uint64_t source) {
const std::string digits{std::to_string(source)};
auto i = digits.begin();
auto j = digits.rbegin();
const auto iend = i + (digits.size() + 1) / 2;
uint64_t result{0};
for (; i < iend; ++i, ++j) {
result *= 10;
result += (*i > *j ? *i : *j) - '0';
}
return result;
}
int main() {
uint64_t n;
std::cin >> n;
std::cout << extract_digits(n) << std::endl;
}
If the task disallows the use of strings and arrays, you could try using pure arithmetics by constructing a “digit-inverted” version of the number and then iterating over both numbers using division and modulo. This will (still) have obvious limitations that stem from the data type size, some numbers cannot be inverted properly etc. (Use GNU MP for unlimited integers.)
#include <cstdint>
#include <iostream>
using std::size_t;
using std::uint64_t;
uint64_t extract_digits(uint64_t source) {
uint64_t inverted{0};
size_t count{0};
for (uint64_t div = source; div; div /= 10) {
inverted *= 10;
inverted += div % 10;
++count;
}
count += 1;
count /= 2;
uint64_t result{0};
if (count) for(;;) {
const uint64_t a{source % 10}, b{inverted % 10};
result *= 10;
result += a > b ? a : b;
if (!--count) break;
source /= 10;
inverted /= 10;
}
return result;
}
int main() {
uint64_t n;
std::cin >> n;
std::cout << extract_digits(n) << std::endl;
}
Last but not least, I would strongly suggest that you ask questions after you have something buildable and runnable. Having homework solved by someone else defeats the homework’s purpose.

How to ignore the blank spacing in array of integers in C++ while reading a number of digits from user input

I want to reverse the array, The code works normally if I give it a input without any blank space but it doesn't work if there is a blank space in it.
e.g. instead of 1234, I give 1 2 3 4 and it would generate incorrect answer.
I tried using conversions from int to string to use getline() to get rid of blank space but that didn't work.
here is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string n, y; // string var declared
int z, rev=0, rem; // int var declared
getline(cin,n); // taken input as sting n
z = stoi(n); // converting sting n to int and storing in z
int *arr = new int(z); // setting z as dynamic array of integers
for (int x=0; x<=z; x++) { // running a loop till x <= z
y = to_string(x); // converting integer x into a string y
cin >> y; // taking inputs as string y
x = stoi(y); // converting string y to integer x
// logic
while(x!=0) { // while int x != 0 run loop
rem=x%10; // finding remainder
rev=rev*10+rem; // adding remainder to var rev i.e reverse
x/=10; // rounding off to remaining numbers
} // closing loop of while
cout<<rev; // printing the final reversed number
} //closing for loop
return 0;
} //closing int main
If you want to process only digits then get rid of everything else with this piece:
getline(cin,n);
std::string inp;
for(auto &s : n)
if (std::isdigit(s)) inp.push_back(s);
Then use inp, it will be free of any non digit characters.
If want to process these digits as independent numbers, you can do this:
std::vector<int> num_inp;
for (auto &s : n)
if (std::isdigit(s))
num_inp.push_back(std::stoi(s));
each digit will be its own number in std::vector.
There are so many possible answers that it is difficult to answer. Either you may use all build in C++ algorithms or, you want a handcrafted solution.
It depends also little bit, if you want to validate the input and allow only digits and spaces or, if you just want to ignore whitespace.
In any case, reading a complete line with std::getline and then do the validation or ignore the spaces or whatever, is the preferred solution.
If you have read the input into str, then you may validate it with a std::regex_match. Or, you can iterate over the string and can check charachter by character.
Ignoring or eliminating the space can be done with std::regex_replace or by putting the std::string into an istringstream and use standard io functions to extract the numbers from there. Using formated input will skip white space.
This is problematic while reading directly from std::cin because finding the and-of-line is -very astonishing- notoriously difficult.
See the following somehow clumsy example:
#include <iostream>
int main() {
unsigned long numberToReverse{};
unsigned long numberTemp{};
// Read as many number parts as existing, even devided by space
while (std::cin >> numberTemp) {
// We need to shift the previous read numbers to the left
// This we do by multiplications of 10. For as many digits as we have in the new part
unsigned long temp{ numberTemp };
do {
numberToReverse *= 10;
} while (temp /= 10);
// Now add the new digits to the right end
numberToReverse += numberTemp;
// In case of '\n', so 'end of line' stop
if (std::cin.peek() == '\n') break;
}
// Reverse digits
unsigned long outputNumber{}; // For output
while(numberToReverse) {
outputNumber *= 10; // Shift digits in output 1 position left
outputNumber += numberToReverse % 10; // Get next digit from input
numberToReverse /= 10; // Look at next digit to the left of the input
}
// Show result
std::cout << outputNumber << '\n';
return 0;
}
OK, it does use only standard iosstream facilities, but it uses peek and will only work, if there is a number directly followed by an '\n' at the end of the input. So, not very good.
Then we may switch to the preferred solution and reada complete line as a string. Put that string into an std::istringstream and extract from there.
#include <iostream>
#include <string>
#include <sstream>
int main() {
unsigned long numberToReverse{};
// Read whateverinput to a string
if (std::string inputAsString{}; std::getline(std::cin, inputAsString)) {
// Put the string into a stringstream toextract the integers
std::istringstream inputAsStringstream{ inputAsString };
// Extract all numbers
unsigned long numberTemp{};
while (inputAsStringstream >> numberTemp) {
// We need to shift the previous read numbers to the left
// This we do by multiplications of 10. For as many digits as we have in the new part
unsigned long temp{ numberTemp };
do {
numberToReverse *= 10;
} while (temp /= 10);
// Now add the new digits to the right end
numberToReverse += numberTemp;
}
}
// Reverse digits
unsigned long outputNumber{}; // For output
while (numberToReverse) {
outputNumber *= 10; // Shift digits in output 1 position left
outputNumber += numberToReverse % 10; // Get next digit from input
numberToReverse /= 10; // Look at next digit to the left of the input
}
// Show result
std::cout << outputNumber << '\n';
return 0;
}
Please note: There is no need to use an array. You can directly calculate each digit by interger and modulo division. And to determin the correct position, we can shift the digits to the left, by multiplication with 10.
These are standard methods and may be found here on SO many times.
And last but not least, the more modern C++ solution, ourely working with strings.
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
// Read string
if (std::string inputAsString{}; std::getline(std::cin, inputAsString))
// Show reversed output
std::copy(inputAsString.crbegin(), inputAsString.crend(), std::ostream_iterator<char>(std::cout));
return 0;
}
You may of course use some validation mechanism after reading the string from std::cin
I Learnt about vectors to resolve this problem, hope this is helpful to someone who might have similar problem in the future.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void display(vector<int> &v)
{
reverse(v.begin(), v.end());
for(int i=0; i < v.size(); i++)
{
cout<<v[i]<<" ";
}
}
int main()
{
vector<int> n;
int size, element;
cout<<"enter the number of elements you want reversed ";
cin>>size;
for(int i=1; i<=size; ++i)
{
//cout<<"Enter elements to be reversed ";
cin>>element;
n.push_back(element);
}
display(n);
return 0;
}
``

How to solve Permutation of a phone number problem

The Problem:
A company is distributing phone numbers to its employees to make things easier. the next digit cannot be equal to the last is the only rule for example 0223 is not allowed while 2023 is allowed. At least three digits will be excluded every time. Write a function that takes in a length of the phone number and the digits that will be excluded. The function should print all possible phone numbers.
I got this question in an interview and I have seen one like it before at my university. It is a permutation problem. My question is what is the best way or decent way to solve this without a million for loops.
I do understand that this is technically how it works
length of phone number = 3;
[0-9], [0-9] excluding the last digit, [0-9] excluding the last digit
but I am unsure on how the best way to turn this into code. Any language is accepted!
thank you:
Also I might be asking this in the wrong place. please let me know if I am.
A simple way to solve this problem could be using Recursion. Here's my commented C++ code:
void solve(int depth, int size, vector <int> &curr_seq){
// If the recursion depth is equal to size, that means we've decided size
// numbers, which means that curr_seq.size() == size. In other words, we've
// decided enough numbers at this point to create a complete phone number, so
// we print it and return.
if(depth == size){
for(int item : curr_seq){
cout << item;
}
cout << "\n";
return;
}
// Try appending every possible digit to the current phone number
for(int i = 0; i <= 9; ++i){
// Make sure to only append the digit i if it is not equal to the last digit
// of the phone number. We can also append it, however, if curr_seq
// is empty (because that means that we haven't decided the 1st digit yet).
if(curr_seq.empty() || curr[curr.size() - 1] != i){
curr_seq.push_back(i);
solve(depth + 1, size, curr);
curr_seq.pop_back();
}
}
}
I think I like the recursive solution, but you can also just generate all permutations up to the limit (iterate), filter out any with repeating digits, and print the successful candidates:
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
// Because C/C++ still has no integer power function.
int ipow(int base, int exp) {
int result = 1;
for (;;) {
if (exp & 1)
result *= base;
exp >>= 1;
if (!exp)
return result;
base *= base;
}
}
void noconsec(const int len) {
int lim = ipow(10, len);
// For e.g. len 4 (lim 10000),
// obviously 00xx won't work, so skip anything smaller than lim / 100.
int start = (len <= 2) ? 0 : (lim / 100);
for (int num = start;num < lim;num++) {
// Convert to string.
std::stringstream ss;
ss << std::setw(len) << std::setfill('0') << num;
std::string num_s = ss.str();
// Skip any consecutive digits.
bool is_okay = true;
auto prev_digit = num_s[0];
for (int digit_idx = 1;digit_idx < num_s.length();digit_idx++) {
auto digit = num_s[digit_idx];
if (prev_digit == digit) {
is_okay = false;
}
prev_digit = digit;
}
// Output result.
if (is_okay) {
cout << num_s << "\n";
}
}
}
int main(const int argc, const char * const argv[]) {
noconsec(4);
}
Differences to note, this needs an integer power function to compute the limit. Converting an int to a string and then checking the string is more complex than constructing the string directly. I guess it could be useful if you have a list of integers already, but mostly I did it for fun.

Decimal to Binary in C++

I'm a total beginner in C++ and today I thought I'd write myself a small program that converts a decimal number to binary. The code looked something like this:
#include <iostream>
void binaryConvert(int);
int main() {
using namespace std;
cout << "Enter decimal number for conversion:" << endl;
int dec;
cin >> dec;
binaryConvert(dec);
}
void binaryConvert(int number) {
using namespace std;
while(number > 0) {
int bin = number % 2;
number /= 2;
cout << bin;
}
}
Logically, this program would print the binary the other way around. I spent a long time trying to figure out how to invert the order of the binary digits so that the binary number would appear the right way around when I came across this piece of code:
void binaryConvert(int number) {
using namespace std;
if(number > 0) {
int bin = number % 2;
number /= 2;
binaryConvert(number);
cout << bin;
}
}
I know its probably a stupid question (I'm an absolute beginner), but I can't figure out why this code prints the bits in the correct order. Also, how come the bits actually get printed if the function gets called again before cout even gets executed?
Basically because "cout" is called after "binaryConvert". It's like putting all the bits in a stack and after that printing them.
It utilizes recursion, the bin at the end will not be printed until the base case is hit (number <= 0) and then it will go up the stack trace.
This function is a recursive one. It is calling itself recursively to print the least significant digits first, before printing out the most significant ones.
int num;
string BinaryRepresentation="";
cout<<"Input:";
cin>>num;
string newstring= "";
bool h;
h = true;
while(h){
BinaryRepresentation += boost::lexical_cast<std::string>( num % 2 );
num = num / 2;
if ( num < 1){
h = false;
}
}
for ( int i = BinaryRepresentation.size() - 1; i >= 0; i--){
newstring += BinaryRepresentation[i];
}
cout<< "Binary Representation: " << newstring <<endl;
}
Mainly the idea of the program is to find the reminder of the number and divide the number by 2 and and keep on repeating the same procedure until the number becomes 0. The you need to reverse the string in order to get the binary equivalent of the entered number.
As you have correctly mentioned your program inverted the binary as it gave the output.
To put the binary in the correct order to The second code starts giving output only once the final bit is obtained. The order of output is bin to the bin and hence we obtain the desired output. The following code may help your understanding further: http://ideone.com/Qm0m7L
void binaryConvert(int number) {
if(number > 0) {
int bin = number % 2;
number /= 2;
cout << bin<<" one"<<endl;
binaryConvert(number);
cout << bin<<" two"<<endl;
}
}
The output obtained is:
0 one
0 one
0 one
1 one
1 two
0 two
0 two
0 two
The output that precedes " one" is what your program would have given.
I hope you understand the difference.
While I was searching online to convert from decimal to binary, didn't find a simple and an understandable solution. So I wrote a program on my own.
Here it goes.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void dtobin(int n)
{
ostringstream oss;
string st="";
if(n<0)
{
cout<<"Number is negative";
return;
}
int r;
while(n!=1)
{
r=n%2;
oss<<st<<r;
n/=2;
}
oss<<st<<1;
st=oss.str();
cout<<st;
//To reverse the string
int len=st.length();
int j=len-1;
char x;
for(int i=0;i<=len/2-1;i++)
{
x=st[i];
st[i]=st[j];
st[j]=x;
--j;
}
cout<<endl<<st;
}
int main()
{
int n;
cout<<"ENTER THE NUMBER";
cin>>n;
dtobin(n);
return 0;
}