I'm doing an online challenge and the challenge is the following:
"Kids are playing a game called "Counting digits". For given numbers S and K, they firstly write all numbers between those numbers and then count how many times each digit appears (0,1,2,3,4,5,6,7,8,9). For example, S=767, K=772, numbers will be: 767,768,769,770,771,772
So, 0 will show once (in 770), 1 will show once (in 771) and so on..
Basically, my program have to do the following (given example):
Input:
1 9
(These are numbers 1,2,3,4,5,6,7,8,9)
Output:
0 1 1 1 1 1 1 1 1 1
(0 doesn't show, other numbers show once)."
I'm stuck on this code... out of ideas.
#include <iostream>
using namespace std;
int main()
{
int s,k;
int array[10];
int c0=0,c1=0,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
cin >> s >> k;
int saves = s;
int savek = k;
cout << s%10;
for(int i=s;i<=k;i++)
{
int savei=i;
while(savei!=0)
{
savei=savei%10;
}
}
Any pseudo code/snippet/code/hint is appreciated.
Purely numeric solution to a purely numeric problem:
#include <iostream>
int main()
{
int s, k, i, tmp;
std::cin >> s >> k;
int count[10] = { 0 };
for (i = s; i <= k; i++) {
tmp = i;
do {
count[tmp % 10]++;
tmp /= 10;
} while(tmp);
}
for (i = 0; i < 10; i++) {
std::cout << i << " appears " << count[i] << " times" << std::endl;
}
return 0;
}
My solution is like this:
int main(){
int s,k;
cin >> s >> k;
int numbers[10]={0};
string sum;
for(int i=s;i<=k;i++)
{
sum=to_string(i);
for(int i=0;i<sum.length();i++){
numbers[(int)sum.at(i)-48]++;
}
}
for(int i=0;i<10;i++){
cout<<numbers[i]<<endl;
}
return 0;
}
public static void getDigitsInBook(int n) {
for(int i=0;i<10;i++) {
int x = n,val=0,k=1;
while(x!=0) {
int left = x/10;
int num = x%10;
int right = n%k;
if(i == 0) {
val = val+ (left*k);
}
else if(i<num) {
val = val + ((left+1)*k);
}
else if(i==num) {
val = val + (left*k) + right+1;
}
else {
val = val+ (left*k);
}
k=k*10;
x = n/k;
}
System.out.println(val);
}
}
What you usually do with such tasks is calculating the number between 0 and S and between 0 and K and subtracting those.
How many are between 0 and 767? First count the numbers of the last digit. There are 77 times 0, 1, 2, 3, 4, 5, 6, 7 each and 76 times 8 and 9. More formally, 767/10+1 between 0 and 767%10 and 767/10+1 on the rest. Then calculate the number of occurences of the last digit for 767/10=76, multiply by 10, add 7 times 7 and 6 (for the error on the last one) and do the same for the remaining digits, here 76/10=7. Finally, add the results up.
This solves the problem in O(log_10 K).
try this code:
for(int n=s ; n<=k ; n++)
{
tempN = abs(n);
while(tempN > 0)
{
tempDigit = tempN % 10;
tempN /= 10;
//count tempDigit here
}
}
assuming your variables are ints, "tempN /= 10;" should be no problem.
Related
#include<bits/stdc++.h>
using namespace std;
int main() {
int n,m,z;
cout<<"enter n: ";
cin>>n;
z=n;
int count=0;
while(n>0){
m = n % 10;
if(z%m == 0){
count++;
}
n=n/10;
}
cout<<count;
}
Code should work like that ex - for n = 12, it is divisible by both 1 , 2 so, the output will be 2
if i am taking any value which have '0' in their last then it is not working ..and i am getting an error "Floating-point exception (SIGFPE)".
Could anyone help me to get rid out of this.
This while loop
while(n>0){
m = n % 10;
if(z%m == 0){
count++;
}
n=n/10;
}
does not make a great sense. For example m can be equal to 0 after this statement
m = n % 10;
and as a result this statement
if(z%m == 0){
produces a run-time error.
The program can look for example the following way
#include <iostream>
int main()
{
unsigned int count = 0;
int n;
std::cout << "enter n: ";
if ( std::cin >> n )
{
const int Base = 10;
int tmp = n;
do
{
int digit = tmp % Base;
if ( digit != 0 && n % digit == 0 ) ++count;
} while ( tmp /= Base );
}
std::cout << "count = " << count << '\n';
}
I have an exercise which looks like that:
Problem statement is simple and straight forward . You will be given a non-negative integer P of length N and you need to check whether
it's divisible by Q ?
Integer P will be given in its decimal representation with P0 as leftmost digit and P1 as second digit from left !
Rest of the digit can be generated from the formula :
Pi = ( 4*Pi-1 + Pi-2 ) modulo Q for 2 <= i <= N-1
Input
The first line contains one integer T - denoting the number of test cases.
T lines follow each containing four integers P0 , P1 , Q and N !
Output
For each testcase output YES if the corresponding integer is divisible by Q and NO otherwise.
Constraints
T <= 100000
0 < P0 , P1 , Q < 10
0 < N <= 1018
Example
Input:
4
1 4 2 2
1 4 2 1
4 2 3 2
3 4 7 3
Output:
YES
NO
YES
NO
Explanation
Value of P is 14, 1, 42, 345 in respective cases !
and that's what I came up with
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int t, q, n, p_0, p_1, p_temp, p;
vector<int> digits;
vector<string> answers;
string number = "";
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> p_0 >> p_1 >> q >> n;
if (n == 1)
{
digits.push_back(p_0);
}
else
{
digits.push_back(p_0);
digits.push_back(p_1);
for (int i = 2; i <= (n - 1); i++)
{
p_temp = (4 * digits[i - 1] + digits[i - 2]) % q;
digits.push_back(p_temp);
}
}
for (int i = 0; i < digits.size(); i++)
{
number += to_string(digits[i]);
}
p = stoi(number);
cout << number << endl;
if (p % q == 0)
{
answers.push_back("YES");
}
else
{
answers.push_back("NO");
}
number = "";
}
for (int i = 0; i < answers.size(); i++)
{
cout << answers[i] << endl;
}
}
Everything I have done works fine, except for one thing, this part does not clear my number variable
number = "";
And honestly I don't know why, could someone correct my mistakes and explain me what did I do wrong. Thanks.
Your problem is with the digits vector.
Each loop the number string just gets repopulated with the digits vector which is never cleared.
Use digits.clear() to empty the vector like so:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int t, q, n, p_0, p_1, p_temp, p;
vector<int> digits;
vector<string> answers;
string number = "";
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> p_0 >> p_1 >> q >> n;
if (n == 1)
{
digits.push_back(p_0);
}
else
{
digits.push_back(p_0);
digits.push_back(p_1);
for (int i = 2; i <= (n - 1); i++)
{
p_temp = (4 * digits[i - 1] + digits[i - 2]) % q;
digits.push_back(p_temp);
}
}
for (int i = 0; i < digits.size(); i++)
{
number += to_string(digits[i]);
}
p = stoi(number);
cout << number << endl;
if (p % q == 0)
{
answers.push_back("YES");
}
else
{
answers.push_back("NO");
}
digits.clear();
number = "";
}
for (int i = 0; i < answers.size(); i++)
{
cout << answers[i] << endl;
}
}
To clear a string you can/should use std::string::clear() as:
number.clear();
There may be other logical errors in your program which may be the reason for not getting the output you expect.
Also instead of creating/initializing the string number using string number = "";, you should use
string number;//no need to write = ""
I have an assignment to make a program that should convert a number from it's integer value to a binary value. For some reason my array is always filled with zeroes and won't add "1"'s from my if statements. I know there are probably solutions to this assignment on internet but I would like to understand what is problem with my code. Any help is appreciated.
Here is what I tried:
#include <iostream>
/*Write a code that will enable input of one real number in order to write out it's binary equivalent.*/
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
while (number > 0) {
int i = 0;
if ((number / 10) % 2 == 0) {
binaryNumber[i] = 0;
}
if ((number / 10) % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 10;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
You need to remove number/10 in both the if statements. Instead, just use number. you need the last digit every time to get the ith bit.
Moreover, you need to just half the number in every iteration rather than doing it /10.
// Updated Code
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
int i = 0;
while (number > 0) {
if (number % 2 == 0) {
binaryNumber[i] = 0;
}
if (number % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 2;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
The first thing is the variable 'i' in the while loop. Consider it more precisely: every time you iterate over it, 'i' is recreated again and assigned the value of zero. It's the basics of the language itself.
The most relevant mistake is logic of your program. Each iteration we must take the remainder of division by 2, and then divide our number by 2.
The correct code is:
#include <iostream>
int main()
{
int x = 8;
bool repr[32]{};
int p = 0;
while(x)
{
repr[p] = x % 2;
++p;
x /= 2;
}
for(int i = 31; i >= 0; --i)
std::cout << repr[i];
return 0;
}
... is always filled with zeroes ... I would like to understand what is problem with my code
int i = 0; must be before the while, having it inside you only set the index 0 of the array in your loop because i always values 0.
But there are several other problems in your code :
using int binaryNumber[32] you suppose your int are on 32bits. Do not use 32 but sizeof(int)*CHAR_BIT, and the same for your last loop in case you want to also write 0 on the left of the first 1
you look at the value of (number / 10) % 2, you must look at the value of number % 2
it is useless to do the test then its reverse, just use else, or better remove the two ifs and just do binaryNumber[i] = number & 1;
number = number / 10; is the right way when you want to produce the value in decimal, in binary you have to divide by 2
in for (int i = 31; i >= 0; i--) { except for numbers needing 32 bits you will write useless 0 on the left, why not using the value of i from the while ?
There are some logical errors in your code.
You have taken (number/10) % 2, instead, you have to take (number %2 ) as you want the remainder.
Instead of taking i = 31, you should use this logic so you can print the following binary in reverse order:
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
Here is the code to convert an integer to its binary equivalent:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to convert integer to binary
void DecBinary(int n)
{
// Array to store binary number
int BinaryNumb[32];
int i = 0;
while (n > 0)
{
// Storing remainder in array
BinaryNumb[i] = n % 2;
n = n / 2;
i++;
}
// Printing array in reverse order
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
}
// Main Program
int main()
{
int testcase;
//Loop is optional
for(int i = 0; i < testcase; i++)
{
cin >> n;
DecToBinary(n);
}
return 0;
}
The program i am designing is for an assignment, but as a do distant learning it is not easy finding a solution.
The program that I have to create must first ask user for an unsigned long int and then break that number down to each digit without repeating number (for example 3344 the program should list 3 and 4), my program just lists all digits. After they have been listed the position of that digits needs to be dispayed with the position (digit at the right is position 0). Then the program should be "reconstruct" to make the original unsigned long int.
An example of what it should look like :
7377683
3 : 0 5
6 : 2
7 : 3 4 6
8 : 1
7377683
The code that i am using currently :
#include <iostream>
using namespace std;
int main()
{
unsigned long int number;
cout << "Enter an integer " << endl;
cin >> number;
for(int i=0; i<10 ; i++)
{
if (number > 0)
{
cout << number%10 << " : " << i; //output digit and position
cout << "\n";
number /= 10;
}
}
return 0;
}
I cannot use arrays or strings to complete this task and that is what i am finding challenging.
You could store digit positions in a decimal bitmask type thing.
unsigned long n, digits[10]{};
// Input
std::cin >> n;
// Break down
for (int i = 1; n; i *= 10, n /= 10)
digits[n % 10] += i;
// Reconstruct and print digit positions
for (int i = 0; i < 10; i++) {
if (!digits[i])
continue;
n += digits[i] * i;
std::cout << i << ":";
for (int j = 0; digits[i]; j++, digits[i] /= 10)
if (digits[i] % 10)
std::cout << " " << j;
std::cout << std::endl;
}
// Output
std::cout << n;
It's kinda neat because you don't need to know how many digits your number has. Also, you could construct the new number and output the positions of all digits in the same loop which you are breaking it down, thus removing the need to store the digits anywhere, but that feels like cheating.
Since you can't use arrays or strings you can probably get away with using an integral type as a bitmap. Any time you output a number in your loop set a bit in the bitmap that corresponds to that number. Then when you need to output that number you check to see if that bit is set and if it is you skip printing it out. Something like the following maybe.
for (int mask = 0, i = 0; i<10; i++)
{
if (number > 0)
{
int value = number % 10;
if ((mask & (1 << value)) == 0)
{
cout << value << " : " << i << endl; //output digit and position
mask |= 1 << value;
}
number /= 10;
}
}
Taking a number down into individual digits works like this:
int number = 4711;
vector<int> v;
while(number > 0)
{
int digit = number % 10;
number /= 10;
v.push_back(digit);
}
Putting it back together again into an integer (we need to go "backwards", as the digits come out "back to front" in the above code)
int number = 0;
for(int i = v.size()-1; i >= 0; i--)
{
number *= 10;
number += v[i];
}
I'm intentionally not showing a complete program to solve your problem, since part of learning programming is to learn how to solve problems. But you sometimes need a few "steps" on the way.
Something like this would solve it with arrays:
int array[10][10] = { { 0 } }; // Position of each digit.
int count[10] = { 0 }; // Number of each digit
int number = 4711;
int pos = 0;
while(number > 0)
{
int digit = number % 10;
number /= 10;
count[digit]++;
array[digit][count[digit]] = pos;
pos++;
}
I'm leaving it to you to fill in the rest of the code (to print and reassemble the number). [The above code doesn't cope with the number zero].
This is the working solution which address to the most crucial problem in your question:
int number = 7377683;
int temp = number;
int pos = 0;
int counter = 0;
int currNum;
int uniqueCount = 0;
Added: Codes to check number of unique digits in number:
for (int x=0; x<9; x++)
for (int y=temp; y>0; y/=10)
if (y%10 == x)
{
uniqueCount ++;
break;
}
Codes to generate the output of every unique elements and positions:
for (int y=0; y<uniqueCount; y++)
{
pos = counter;
currNum = number%10;
cout << temp%10 << " : ";
for (int x=temp; x>0; x/=10)
{
if (temp%10 == currNum)
cout << pos << " ";
pos++;
temp /= 10;
}
counter++;
number /=10;
temp = number;
cout << endl << endl;
}
Program Output:
3 : 0 5
8 : 1
6 : 2
7 : 3 4 6
This solution is using the most basic construct without array (according to your requirements).
I have an integer:
int iNums = 12476;
And now I want to get each digit from iNums as integer. Something like:
foreach(iNum in iNums){
printf("%i-", iNum);
}
So the output would be: "1-2-4-7-6-".
But i actually need each digit as int not as char.
Thanks for help.
void print_each_digit(int x)
{
if(x >= 10)
print_each_digit(x / 10);
int digit = x % 10;
std::cout << digit << '\n';
}
Convert it to string, then iterate over the characters. For the conversion you may use std::ostringstream, e.g.:
int iNums = 12476;
std::ostringstream os;
os << iNums;
std::string digits = os.str();
Btw the generally used term (for what you call "number") is "digit" - please use it, as it makes the title of your post much more understandable :-)
Here is a more generic though recursive solution that yields a vector of digits:
void collect_digits(std::vector<int>& digits, unsigned long num) {
if (num > 9) {
collect_digits(digits, num / 10);
}
digits.push_back(num % 10);
}
Being that there are is a relatively small number of digits, the recursion is neatly bounded.
Here is the way to perform this action, but by this you will get in reverse order.
int num;
short temp = 0;
cin>>num;
while(num!=0){
temp = num%10;
//here you will get its element one by one but in reverse order
//you can perform your action here.
num /= 10;
}
I don't test it just write what is in my head. excuse for any syntax error
Here is online ideone demo
vector <int> v;
int i = ....
while(i != 0 ){
cout << i%10 << " - "; // reverse order
v.push_back(i%10);
i = i/10;
}
cout << endl;
for(int i=v.size()-1; i>=0; i--){
cout << v[i] << " - "; // linear
}
To get digit at "pos" position (starting at position 1 as Least Significant Digit (LSD)):
digit = (int)(number/pow(10,(pos-1))) % 10;
Example: number = 57820 --> pos = 4 --> digit = 7
To sequentially get digits:
int num_digits = floor( log10(abs(number?number:1)) + 1 );
for(; num_digits; num_digits--, number/=10) {
std::cout << number % 10 << " ";
}
Example: number = 57820 --> output: 0 2 8 7 5
You can do it with this function:
void printDigits(int number) {
if (number < 0) { // Handling negative number
printf('-');
number *= -1;
}
if (number == 0) { // Handling zero
printf('0');
}
while (number > 0) { // Printing the number
printf("%d-", number % 10);
number /= 10;
}
}
Drawn from D.Shawley's answer, can go a bit further to completely answer by outputing the result:
void stream_digits(std::ostream& output, int num, const std::string& delimiter = "")
{
if (num) {
stream_digits(output, num/10, delimiter);
output << static_cast<char>('0' + (num % 10)) << delimiter;
}
}
void splitDigits()
{
int num = 12476;
stream_digits(std::cout, num, "-");
std::cout << std::endl;
}
I don't know if this is faster or slower or worthless, but this would be an alternative:
int iNums = 12476;
string numString;
stringstream ss;
ss << iNums;
numString = ss.str();
for (int i = 0; i < numString.length(); i++) {
int myInt = static_cast<int>(numString[i] - '0'); // '0' = 48
printf("%i-", myInt);
}
I point this out as iNums alludes to possibly being user input, and if the user input was a string in the first place you wouldn't need to go through the hassle of converting the int to a string.
(to_string could be used in c++11)
I know this is an old post, but all of these answers were unacceptable to me, so I wrote my own!
My purpose was for rendering a number to a screen, hence the function names.
void RenderNumber(int to_print)
{
if (to_print < 0)
{
RenderMinusSign()
RenderNumber(-to_print);
}
else
{
int digits = 1; // Assume if 0 is entered we want to print 0 (i.e. minimum of 1 digit)
int max = 10;
while (to_print >= max) // find how many digits the number is
{
max *= 10;
digits ++;
}
for (int i = 0; i < digits; i++) // loop through each digit
{
max /= 10;
int num = to_print / max; // isolate first digit
to_print -= num * max; // subtract first digit from number
RenderDigit(num);
}
}
}
Based on #Abyx's answer, but uses div so that only 1 division is done per digit.
#include <cstdlib>
#include <iostream>
void print_each_digit(int x)
{
div_t q = div(x, 10);
if (q.quot)
print_each_digit(q.quot);
std::cout << q.rem << '-';
}
int main()
{
print_each_digit(12476);
std::cout << std::endl;
return 0;
}
Output:
1-2-4-7-6-
N.B. Only works for non-negative ints.
My solution:
void getSumDigits(int n) {
std::vector<int> int_to_vec;
while(n>0)
{
int_to_vec.push_back(n%10);
n=n/10;
}
int sum;
for(int i=0;i<int_to_vec.size();i++)
{
sum+=int_to_vec.at(i);
}
std::cout << sum << ' ';
}
The answer I've used is this simple function:
int getDigit(int n, int position) {
return (n%(int)pow(10, position) - (n % (int)pow(10, position-1))) / (int)pow(10, position-1);
}
Hope someone finds this helpful!
// Online C++ compiler to run C++ program online
#include <iostream>
#include <cmath>
int main() {
int iNums = 123458;
// int iNumsSize = 5;
int iNumsSize = trunc(log10(iNums)) + 1; // Find length of int value
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
// The pow() function returns the result of the first argument raised to
the power of the second argument.
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d ",z - x2*10 ); // Print Values
}
return 0;
}
You can do it using a while loop and the modulo operators.
It just gives the digits in the revese order.
int main() {
int iNums = 12476;
int iNum = 0;
while(iNums > 0) {
iNum = iNums % 10;
cout << iNum;
iNums = iNums / 10;
}
}
int a;
cout << "Enter a number: ";
cin >> a;
while (a > 0) {
cout << a % 10 << endl;
a = a / 10;
}
int iNums = 12345;
int iNumsSize = 5;
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d-",z - x2*10 );
}