No repeating digits and reconstructing int - c++

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).

Related

Converting an integer into it's binary equivalent

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;
}

Private test cases are not passing. What is the mistake here? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Given N three-digit numbers, your task is to find bit score of all N numbers and then print the number of pairs possible based on these calculated bit score.
Rule for calculating bit score from three digit number:
From the 3-digit number,
· extract largest digit and multiply by 11 then
· extract smallest digit multiply by 7 then
· add both the result for getting bit pairs.
Note: - Bit score should be of 2-digits, if above results in a 3-digit bit score, simply ignore most significant digit.
Consider following examples:
Say, number is 286
Largest digit is 8 and smallest digit is 2
So, 8*11+2*7 =102 so ignore most significant bit , So bit score = 02.
Say, Number is 123
Largest digit is 3 and smallest digit is 1
So, 3*11+7*1=40, so bit score is 40.
Rules for making pairs from above calculated bit scores
Condition for making pairs are
· Both bit scores should be in either odd position or even position to be eligible to form a pair.
· Pairs can be only made if most significant digit are same and at most two pair can be made for a given significant digit.
Constraints
N<=500
Input Format
First line contains an integer N, denoting the count of numbers.
Second line contains N 3-digit integers delimited by space
Output
One integer value denoting the number of bit pairs.
Test Case
Explanation
Example 1
Input
8 234 567 321 345 123 110 767 111
Output
3
Explanation
After getting the most and least significant digits of the numbers and applying the formula given in Rule 1 we get the bit scores of the numbers as:
58 12 40 76 40 11 19 18
No. of pair possible are 3:
40 appears twice at odd-indices 3 and 5 respectively. Hence, this is one pair.
12, 11, 18 are at even-indices. Hence, two pairs are possible from these three-bit scores.
Hence total pairs possible is 3
#include <iostream>
#include <vector>
using namespace std;
vector<int> correctBitScores(vector<int>);
vector<int> bitScore(vector<int>);
int findPairs(vector<int>);
int main() {
int a, b;
int pairs = 0;
vector<int> vec;
vector<int> bitscore;
cout << "\nEnter count of nos: ";
cin >> a;
for (int i = 0; i < a; i++) {
cin >> b;
vec.push_back(b);
}
bitscore = bitScore(vec);
pairs = findPairs(bitscore);
cout << "Max pairs = " << pairs;
return 0;
}
vector<int> correctBitScores(vector<int> bis) {
int temp = 0;
for (size_t i = 0; i < bis.size(); i++) {
temp = bis[i];
int count = 0;
while (temp > 0) {
temp = temp / 10;
count++;
}
if (count > 2)
bis[i] = abs(100 - bis[i]);
}
/*cout << "\nCorrected" << endl;
for (int i = 0; i < size(bis); i++) {
cout << bis[i] << endl;
}*/
return bis;
}
int findPairs(vector<int> vec) {
int count = 0;
vector<int> odd;
vector<int> even;
for (size_t i = 0; i < vec.size(); i++)
(i % 2 == 0 ? even.push_back(vec[i]) : odd.push_back(vec[i]));
for (size_t j = 0; j < odd.size(); j++)
for (size_t k = j + 1; k < odd.size(); k++) {
if (odd[j] / 10 == odd[k] / 10) {
count++;
odd.erase(odd.begin()+j);
}
}
for (size_t j = 0; j < even.size(); j++)
for (size_t k = j + 1; k < even.size(); k++) {
if (even[j] / 10 == even[k] / 10) {
count++;
even.erase(even.begin() + j);
}
}
return count;
}
vector<int> bitScore(vector<int> v) {
int temp = 0, rem = 0;
vector<int> bs;
for (size_t i = 0; i < v.size(); i++) {
int max = 0, min = 9;
temp = v[i];
while (temp > 0) {
rem = temp % 10;
if (min > rem)
min = rem;
if (max < rem)
max = rem;
temp = temp / 10;
}
int bscore = (max * 11) + (min * 7);
bs.push_back(bscore);
}
/*cout << "\nBit Scores = " << endl;
for (int i = 0; i < size(bs); i++) {
cout << bs[i] << endl;
}*/
bs = correctBitScores(bs);
return bs;
}
I tried doing it very simple c++ code as per my understanding of Que,can you just verify it more test cases.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,count=0;
cin>>n;
vector<int>v(n);
for(int i=0;i<n;i++){
cin>>v[i];
string s = to_string(v[i]);
sort(s.begin(),s.end());
int temp = (s[s.length()-1]-'0')*11 + (s[0] - '0')*7;
v[i] = temp%100;
}
unordered_map<int ,vector<int>>o,e;
for(int i=0;i<n;i=i+2){
o[v[i]/10].push_back(i+1);
}
for(int i=1;i<n;i=i+2){
e[v[i]/10].push_back(i+1);
}
count=0;
for(int i=0;i<10;i++){
int os=o[i].size(),es=e[i].size();
if(os==2)
count++;
if(es == 2)
count++;
if(os>2 || es>2)
count += 2;
}
cout<<count;
}

Number of time the iterative function is called

Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.
However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
First, initialize the variable
c1 = 0;
so that you will not get any garbage value get printed.
Secondly this:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1 your count. You don't need that.
Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.
Thirdly,
for (int x = 0; x <= num; x++)
you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.
If you meant to start from x = 1, you need this:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}

C decimal to binary without arrays

I think I've almost got it, but I feel like I'm go in circles trying to figure this out.
The challenge to out cout without using strings or arrays. I took the number 56 as an example and 56 should equal 111000 this is not the case as it goes through fine till 7 then the number equals number*2 + number%2 makes it equal to 15 and outputs all 1's. Idk anymore, this is driving me to the moon and back.
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int n = 1;
int x = n;
cin>>number;
cout<<n%2;
while(n <= number)
{
if(n%2 == 0)
{
n = n*2;
cout<<0;
}
else
{
n = n*2 + n%2;
cout<<n%2;
}
}
}
You can use the binary operator & to check if a single bit is 1 or 0.
for (int i=512; i>0; i/=2) {
cout << ( ( number & i ) != 0 ) ;
}
Note that this WILL print leading 0's.
Also, I'm assuming you only want to print positive integers.
Alternative:
for (int i=512; i>0; i/=2) {
if (number >= i) {
cout << 1;
number -= i;
} else {
count << 0;
}
}
You can use recursion
void decimal_to_binary(int decimal)
{
int remainder = decimal % 2;
if (decimal < 1)
return;
decimal_to_binary(decimal / 2);
cout << remainder;
}
This function will take the decimal, get its remainder when divided to 2. Before it the function call itself again, it checks if the decimal is less than 1(probably 0) and return to execute the printing of 1's and 0's
I had this type of problem assigned to me recently. This code example work up to a maximum of 10 binary digits (per the problem guidelines) and keep prompting for input until 0 is entered (sentinel value). This can certainly be improved but the math is correct:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
//Declare Variables
int inputValue = 0;
int workingValue = 0;
int conversionSum = 0;
//Begin Loop
do{
//Prompt for input
cout << "Enter a binary integer (0 to quit): ";
cin >> inputValue;
//Reset Variables
workingValue = inputValue;
conversionSum = 0;
//Begin processing input
//10 digits max, so 10 iterations
for (int i=0; i<10; i++) {
//Check for non-binary entry
if ((workingValue % 10) != 1 && (workingValue % 10 != 0)){
cout << "Invalid!\n";
workingValue = 0;
conversionSum = 0;
break;
}
//check to see if 2^i should be added to sum
if (workingValue%2 == 1){
conversionSum += pow(2,i);
workingValue--;
}
//divide by 10 and continue loop
workingValue= workingValue / 10;
}
//output results
cout << "converted to decimal is: " << conversionSum << endl;
}while (inputValue != 0);
}
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
cout << "enter a number";
int number, n, a=0;
cin >> number;
n = number;
do
{
n=n/2;
a=a+1;
}
while (n>=1);
cout << "a is" << a;
int c = a;
int b = a;
cout << "binary is";
for(int i=0; i<=c; i++)
{
int k = number / pow(2,b);
cout << k;
number = number - k * pow(2,b);
b = b-1;
}
return 0;
}
Although asked in C I have used C++. I have used the logic that if you have to convert decimal to binary we have to find the maximum power of 2 contained in the number which when added by 1 becomes the number of digit of required binary .. leftmost digit is the number of highest available power of 2 (ex in 8 highest power of 2 is 3 and 1 such is available)...then subtract this from the number and (ex 8-8=0)and search for number of next highest available power of 2 and so on.

C++ get each digit in int

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 );
}