Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In case of normal integer, we use %10 for the remainder, and /10 to reduce the digit by one digit.
For a Binary Digit, I could use %2 to get the remainder, but how do I remove digits from the Binary number?
If there's a number 0000, when I perform /10, I need 000 and not 0.
while (bin > 0) {
int rem = bin % 2;
// action_block;
// How do I divide ?
}
Clearing the confusion, this is for a problem of a competitive coding site. The stdin will be an integer, which has a binary data. Example: 1100001. I want its bits in an array. arr[0] = 1, arr[1] = 1, arr[2] = 0, arr[3]=0 and so on..
Quite logically, use /2. It's the same with any base.
Right shift (>>) operator is used to shift the bits to right by position specified in the expression.
For example :
unsigned int num1 = 12; // 12 = 1100
int num2 = 0;
num2 = num1 >> 1; // 6 = 0110
int num3 = 0;
num3 = num1 >> 2; // 3 = 0011
Now, try achieving your goal using this.
Edit :
As problem described by OP in comment section of this answer.
std::string inp;
std:: cin >> inp.
for (int i = 0; i < inp.length(); i++) {
std::stoi(inp[i]); // This will be 0,1.
}
If you want to use an array then this is what you are looking for :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input="0101011010";
int arr[10];
for(int i=0; i<10; i++)
{
arr[i]=input[i]-'0';
}
for(int i=0; i<10; i++)
{
cout << arr[i] << endl;
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am a student in my first year.
Could someone help me with an assignment?
Simple calc C++
In the first line the number of tests n. In the next n lines operations Each operation contains the operation type (+ *) the number of k numbers to be processed, and k numbers
Output
Result
Example
Input
3
+ 3 3.1 5.2 -8.3
* 2 1 3.3
+ 1 3
Output
0
3.3
3
My code
int n, k;
char x;
cin >> n;
int tab[100];
for (int i = 0; i < n; i++)
{
cin >> x >> k;
for (int j = 0; j < k; j++)
{
cin >> tab[j];
if (x == '+')
{
tab[j] += tab[j + 1];
}
if (x == '*')
{
tab[j] *= tab[j + 1];
}
cout << tab[j];
}
}
return 0;
}
There are a few problems.
your tab is of type int so it can only store integers e.g.: 1,2,3,4,5 not floating point numbers like 1.3 2.5 3.3, you should consider changing tab to be of type float.
your loop logic and indexing is totally wrong, and you are accessing the wrong elements, you should have some sort of accumulator variable that will accumulate the results instead of storing them in an array. e.g.:
float accumulator = 0;
cin >> input_number;
accumulator += input_number;`
the best advice i can give you is to learn to use the debugger, the debugger is your friend, you should use it to walk through your code, line by line and understand what each lines does to each variable, and read the contents of each variable, i cannot recommend a certain source for learning to use a debugger as it depends on your IDE, but you should maybe check a video on using debugger with IDE X, it can be a good start for learning to use an IDE GUI.
The issues are many. Just some:
The purpose of tab is unclear. You do not need to store the operands, you can accumulate a result in a single value.
In any event tab[j + 1]; is not initialised at point of use.
If you want to output the results after all the input as indicated in the question then you do need somewhere to store the results for later output.
You do need to output the results.
The input and output types do need to be a floating-point type.
Greater clarity of thought might arise if you were to use clear variable names that reflected their purpose and perhaps some comments. If you have to explain what the code does (even to yourself) often you spot the errors. A good technique is to write the comments first, to explain what you need to code rather than explaining the code you have written and assume erroneously to be correct. Also you need to get out of that "all variables at the top" habit.
Example:
#include <iostream>
int main()
{
// Get number of calculations
int ncalc = 0 ;
std::cin >> ncalc ;
// Create array for results
double* result = new double[ncalc] ;
// For each calculation
for( int calc = 0; calc < ncalc; calc++ )
{
// Get the operator
char op = 0 ;
std::cin >> op ;
// Get the number of operands
int noperands = 0 ;
std::cin >> noperands ;
// Get initial operand in accumulator
double accumulator = 0 ;
std::cin >> accumulator ;
// For each remaining operand...
for( int i = 1; i < noperands; i++)
{
// Get the operand
double operand = 0 ;
std::cin >> operand ;
// Perform the operation
switch( op )
{
// For +, accumulate sum
case '+' : accumulator += operand ; break ;
// For * accumulate product
case '*' : accumulator *= operand ; break ;
}
}
// Store accumulated result
result[calc] = accumulator ;
}
// Output results
for( int calc = 0; calc < ncalc; calc++ )
{
std::cout << result[calc] << '\n' ;
}
delete[] result ;
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
---How write a program that will get A and B inputs and the numbers in the [A, B] range will be divisible by 7 without the remainder... using while loop in C++...---
For Example:
Input data: 7 13
console result: 1
Input data 5 21
console result: 3
Input data -8 -5
console result: 1
C++ code example with for loop
int main() {
int a, b,i,count;
input >> a >> b;
count = 0;
for(i = a; i <= b; i++) {
if(i % 7 == 0)
count++
}
}
I'm not sure if this is pseudo-code or actual code, but the main mistake I see here is that you've used 'input' and I'm not sure what that's supposed to be. See the following example:
#include <iostream>
using namespace std;
int main() {
int count=0;
int a = 0;
int b = 0;
cin >> a >> b;
for(int i = a; i <= b; i++) {
if(i % 7 == 0) {
count++;
}
}
cout << count;
}
I replaced your 'input' with 'cin'. Then, I added an output of the 'count' variable so that we could see the result.
Now, to take it further and use a while loop, you just need to manually count:
#include <iostream>
using namespace std;
int main() {
int count=0;
int a = 0;
int b = 0;
cin >> a >> b;
while (a <= b) {
if (a % 7 == 0) {
count++;
}
a = a +1;
}
cout << count;
}
So, we simply need to say while a is less than or equal to b, do the same thing as before. But, make sure that you increase a, or your loop will go on forever!
Everything is correct in terms of pseudo code. Do you want the negative number to be included or not?
Anyway, I am counting negative numbers also.
#include <iostream>
int main()
{
int a, b, i, count = 0;
std::cin >> a >> b;
i = a;
while (i <= b) // While loop
{
if (i % 7 == 0)
{
count++;
}
i++;
}
std::cout << "Count: " << count << "\n";
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is there a way to get the number of digits without the division by 10?
For example i have this:
int main()
{
int dividend = 100;
int remainder=0;
int temp = 0;
while(dividend>=10)
{
dividend = dividend-10;
temp+=1;
}
printf("Quotient: %d\n",temp);
printf("Reminder: %d\n",dividend);
}
And now I will add to calculate the number of digits of the variable dividend.
You have to know the maximum range of integer to make this function usefull.
no function call, no division ...
int nbDigitInteger(int number)
{
if (-10 < number && number < 10) return (1);
if (-100 < number && number < 100) return (2);
if (-1000 < number && number < 1000) return (3);
if (-10000 < number && number < 10000) return (4);
if (-100000 < number && number < 100000) return (5);
...
}
Sometime, the simplier is the best.
If you are allowed to use logarithms then
int i = 123456;
int digitsCount = ceil(log10(abs(i)+1.0));
cout << digitsCount;
6
Your question is too broad, and the code is also unrelated.
Since you attempted to post the code, I'll provide the guidelines for the problem you asked for. Write the code yourself.
Take the absolute integer value. (abs())
Print it to a (large enough) buffer. (sprintf()/ snprintf()).
Use strlen() to get the length of the buffer (as string).
An alternative to the very elegant solution o #Yola is this.
intPow10 is returning 10 to the power exponent. I did not use pow from math.h, since it is numerically expensive and as #Tom's pointed out it can lead to invalid results.
#include <stdio.h>
#include<math.h>
int intPow10(int exponent){
int retval=1;
while (exponent){
retval *=10;
exponent --;
}
return retval;
}
int numDigits(const int i) {
int digits = 1;
while (intPow10(digits) <= fabs(i)) {
digits++;
}
printf("%i has %i digits.\n", i,digits);
return digits;
}
int main() {
numDigits(1);
numDigits(-1);
numDigits(10);
numDigits(13);
numDigits(-112312);
}
Is this code golf or what?
int b = 1000;
char a[10] = itoa(b);
printf("%d\n", strlen(a)); // 4
This simply turns b into a string, which is a. Then, prints the length. What would we do without atoi() and itoa()? Our own functions!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to solve an exercise. It says that i need to output 3 last digits of a number that is 2 raised to the power of n (2^n).
But input is n=1000000.
The code works with lower values, but when the input is 1 000 000 the number gets too large.
My code:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
unsigned long long n;
cin >> n;
unsigned long long sk = pow(2, n);
if (sk < 1000) cout << sk;
else {
string ats = to_string(sk); // converting the number to string
// so I could output 3 last digits
// probably not the best solution
// for this exercise
n = ats.length();
for (unsigned long long i = n - 3; i < n; i++) {
cout << ats[i];
}
}
return 0;
}
Thank you for your help.
Try something like:
Initialize result to 1
Within a loop from 1 to n:
result *= 2
result %= 1000
This because the result of the last 3 digits does not depend upon the greater digits
You can calculate your number modulo 1000. Just saving the three least significant digits and trashing the more significant ones does not alter the result.
Just do:
int result = 1;
for(int i = 0; i < n; i++){
result = (result * 2) % 1000;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm working on a C++ project and have run into an issue that is leaving me puzzled. I am to create a phone number generator that has the user enter the first 4 numbers, and then generate all possible phone numbers that follow these two rules:
The last 6 digits must equal 33.
The 4th and 5th digit cannot both be even or both be odd.
This is what I've come up with so far:
#include <iostream>
using namespace std;
int main()
{//begin main
srand(time(0));
const int MAX_DIGITS = 10;
int num[MAX_DIGITS] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
cout<<"enter the first digit: ";
cin>>num[0];
cout<<"Enter the second digit: ";
cin>>num[1];
cout<<"Enter the third digit: ";
cin>>num[2];
cout<<"Enter the fourth digit: ";
cin>>num[3];
for (int e=0;e<MAX_DIGITS;e++)
{
for(int f=0;f<MAX_DIGITS;f++)
{
for(int g=0;g<MAX_DIGITS;g++)
{
for(int h=0;h<MAX_DIGITS;h++)
{
for(int i=0; i<MAX_DIGITS;i++)
{
for(int j=0;j<MAX_DIGITS;j++)
{
if ((num[e]+num[f]+num[g]+num[h]+num[i]+num[j]) == 33 && (num[3]%2 != 0 && num[4]%2 != 0) )
{
cout<<num[0]<<num[1]<<num[2]<<num[3]<<num[e]<<num[f]<<num[g]<<num[h]<<num[i]<<num[j]<<endl;
}
}
}
}
}
}
}
It all makes sense to me so far, but the program is displaying some numbers multiple times, and I'm not entirely certain how to make sense of the even/odd rule.
I'm still a rookie to programming and I'm sure that there may be a more efficient way to do this, but I'm trying my best and this has left me puzzled. Any help would be appreciated.
Thanks in advance!
EDIT: My question is this, how do I get the generator to display the numbers with the even/odd rule applied? My best idea was to use the modulus operator (%) to see if the remainder of the numbers divided by two was zero, and if so, the numbers were even. This is where I stumble a bit though, because I'm not perfectly certain how to implement this. Sorry for not being more specific the first time.
1) You're not ever changing the values in the num array, so testing to see if it contains a valid number doesn't work because the initial values you set don't fit the rules.
2) The validation is checking to see if both numbers are odd, not one or the other.
Here's a version that seems to work. The changes I made are to actually change the num array and then use a helper function to validate the numbers in the array so you don't have a mess inside your loops. I removed the srand call since you aren't using random numbers and the input of the first 4 digits to make testing easier for me. You can add that back if you like.
#include <iostream>
const int MAX_DIGITS = 10;
bool IsValid(int num[MAX_DIGITS])
{
int sum = 0;
for(int z = 4; z < MAX_DIGITS; ++z)
{
sum += num[z];
}
if(sum != 33)
{
return false;
}
int numodd = 0;
for(int z = 3; z < 5; ++z)
{
numodd += (num[z] % 2);
}
if(numodd != 1)
{
return false;
}
return true;
}
int main()
{
int num[MAX_DIGITS];
num[0] = 5;
num[1] = 5;
num[2] = 5;
num[3] = 1;
for (int e=0;e<MAX_DIGITS;e++)
{
num[4] = e;
for(int f=0;f<MAX_DIGITS;f++)
{
num[5] = f;
for(int g=0;g<MAX_DIGITS;g++)
{
num[6] = g;
for(int h=0;h<MAX_DIGITS;h++)
{
num[7] = h;
for(int i=0; i<MAX_DIGITS;i++)
{
num[8] = i;
for(int j=0;j<MAX_DIGITS;j++)
{
num[9] = j;
if(IsValid(num))
{
for(int z = 0; z < MAX_DIGITS; ++z)
{
if(z == 3 || z == 6)
{
std::cout << '-';
}
std::cout << num[z];
}
std::cout << std::endl;
}
}
}
}
}
}
}
}