C decimal to binary without arrays - c++

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.

Related

Sum of digits of N to the power P

My C++ code is supposed to take a number and an exponent as integer inputs, calculate the 'number' to the power of THAT 'exponent' and sum the digits of the result and output it. It works well for small exponent values like 10 or 20, but gives wrong answers for large values like ~ >500. I have limited my 'number' inputs to <5 for wease of computability. I cannot figure out what is wrong with my logic.
#include<iostream>
using namespace std;
#include <cmath>
int main(){
int number, exponent;
cin >> number >> exponent;
double product = 1;
int sum = 0;
// Write your code here
for (int i = 0; i < exponent; i++){
product = product * number;
}
cout << "THE MAIN PRODUCT IS: " << product << "\n\n";
while (product > 1){
sum = sum + fmod(product, 10.0); // kEEP ADDING THE DIGITS TO THE SUM
cout << "sum is " << sum << endl;
product = product / 10.000;
cout << "product is " << product << endl;
}
cout << endl;
cout << sum << endl;
}
The issue with a large exponent is the length of the final answer or the number of digits in the final answer.
In C++, the largest integer that can be represented is 18-19 digits.
If the number exceeds beyond a limit, it will cause an integer overflow.
So, the best way to tackle this problem is to make use of strings or integer arrays.
Have a look at the following implementation:
#include <iostream>
#include <math.h>
// Maximum number of digits in
// output
#define MAX 100000
int multiply(int x, int res[], int res_size) {
// Initialize carry
int carry = 0;
// One by one multiply n with
// individual digits of res[]
for (int i = 0; i < res_size; i++) {
int prod = res[i] * x + carry;
// Store last digit of
// 'prod' in res[]
res[i] = prod % 10;
// Put rest in carry
carry = prod / 10;
}
// Put carry in res and
// increase result size
while (carry) {
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
}
return res_size;
}
// This function finds
// power of a number x
long long power(int x, int n)
{
//printing value "1" for power = 0
if(n == 0 ){
return 1;
}
int res[MAX];
int res_size = 0;
int temp = x;
// Initialize result
// Representing base in reverse form
while (temp != 0) {
res[res_size++] = temp % 10;
temp = temp / 10;
}
// Multiply x n times
// (x^n = x*x*x....n times)
for (int i = 2; i <= n; i++)
res_size = multiply(x, res, res_size);
long long final_answer = 0;
//Finally taking sum of all the digits in the answer.
for(int i=0;i<res_size; i++){
final_answer += res[i];
}
return final_answer;
}
int main() {
int exponent = 8;
int base = 34;
std::cout<<power(base, exponent);
return 0;
}
Output:
76

Count the number of digits in a Binary

For this program, I will input a Binary number and it will convert into a decimal number. At the end I wanted to return the number of digits in the Binary number that I had input. For example, 1001 - 4 Binary digits.The output of the digits of Binary number is always 0. Should I use size_type to do it ?
#include<iostream>
#include<string>
#include<bitset>
#include<limits>
#include<algorithm>
using namespace std;
int multiply(int x);
int multiply(int x)
{
if (x == 0)
{
return 1;
}
if (x == 1)
{
return 2;
}
else
{
return 2 * multiply(x - 1);
}
}
int count_set_bit(int n)
{
int count = 0;
while (n != 0)
{
if (n & 1 == 1)
{
count++;
}
n = n >> 1;
}
return count;
}
int main()
{
string binary;
cout << "\n\tDualzahlen : ";
cin >> binary;
reverse(binary.begin(), binary.end());
int sum = 0;
int size = binary.size();
for (int x = 0; x < size; x++)
{
if (binary[x] == '1')
{
sum = sum + multiply(x);
}
}
cout << "\tDezimal : " << sum << endl;
int n{};
cout << "\tAnzahl der Stelle : " << count_set_bit(n) << endl;
}
It looks like you are on the right track for unsigned integers. Signed integers in a multiply are generally converted to positive with a saved result sign.
You can save some time with a bit data solution, as value testing is not cost free plus 'and' has no carry delay. Of course, some CPUs can ++ faster than += 1, but hopefully the compiler knows how to use that:
int bits( unsigned long num ){
retVal = 0 ;
while ( num ){
retVal += ( num & 1 );
num >>= 1 ;
}
return retVal ;
}
I recall the H-4201 multiplied 2 bits at a time, using maybe shift, maybe add, maybe carry/borrow, so 0 was no add, 1 was add, 2 was shift and add, 3 was carry/borrow add (4 - 1)! That was before IC multiply got buried in circuits and ROMs. :D

A C++ program that gets 100 integers and finds the possibly given negative ones

I'm trying to write the code for a C++ program which will get some numbers (integers) and will put them into a 100 sized array, and will begin searching for possibly given negative ones (Negative of given positive numbers) after the user had inputted the sentinel number (101). For example; when we give the integers 1, 45, 12, -32, 103, 2015 and 32 to the program, it should give us the the integer 32 (because the negative form of it is existing) and if there were no numbers with this statement, then it will prints nothing. I wrote something like below; but I don't know how to do the rest... Any help or suggestions are appreciated.
I forgot to say that I use CodeBlocks 13.12 .
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){
cin >> number;
myArray[0]= number;
nCounter += 1;
}
for ( i = 0; i <= nCounter; i++ ){
if (myArray[i] > 0) // I'm stuck at here!
}
return 0;
}
Thanks and please apologize for possible English mistakes.
Here are some mistakes in the code :
First, you are assigning all the input elements to the 0th indexed element of the array.
The user can very well give 200 elements without typing 101, in that case you will overrun your array size.
A simple algorithm should be like this:
Pick the ith positive element and search through out the array for its negative.
Repeat 1 for every possible positive element in the array.
Here is a working example.
The input should be like this :
while ( (nCounter < 100) && (number != sentinel) ) {
std::cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
And the checking condition:
for ( i = 0; i < nCounter; i++ ){
if (myArray[i] > 0) {
for( j = 0; j < nCounter; j++) {
if(myArray[i] + myArray[j] == 0) // positive and negative add up to 0
std::cout << myArray[i] << std::endl ;
}
}
}
Here's a slight modification of your code that will get you what you need
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i, negMatch;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){
cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
cout << "Enter the number to negative match";
cin >> negMatch;
for ( i = 0; i < nCounter; i++ ){
if ( (myArray[i] + negMatch) == 0) {
cout << myArray[i];
return 0;
}
}
return 0;
}
Please note the following changes:
You were inserting all the elements into the first slot, I changed it so that you enter them in the correct spot
Getting the number to be matched as input (negMatch is "32" in your question)
Modified the loop to check the numbers
However, this program is not ideal. Ideally, you would use something like Vectors, which can dynamically grow. Also, it might be better to have the user input the count of numbers, instead of using a sentinel number that he might want to give as input.
If I understand this correctly you want to print the negative ones but with positive sign. With this simple code you can do it!
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( (nCounter < 100) && (number != sentinel) ) {
std::cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
for (int i = 0; i < nCounter; i++ ){
if (myArray[i] < 0) {
std::cout << (myArray[i] * -1) << std::endl ;
}
}
return 0;
}
A simple change that reduce the computational cost is the following: you can try to get information from the number given when you read it
#include <iostream>
#include <vector>
using namespace std;
int number = 0, sentinel = 101;
int main (){
cout << "Please enter your numbers: " << endl;
vector<int> array;
while (number != sentinel) {
std::cin >> number;
if(number < 0)
array.push_back(number);
}
for (int i = 0; i < array.size(); i++ )
std::cout << (array[i] * -1) << std::endl ;
return 0;
}
I suggest to write positive numbers in the beginning of the array and negative numbers in the end of the array.
Here is a demonstrative program
#include <iostream>
int main()
{
const size_t N = 100;
const int SENTINEL = 101;
int a[N];
int number;
size_t positive_end = 0;
size_t negative_begin = N;
for ( size_t i = 0; i < N && std::cin >> number && number != SENTINEL; i++ )
{
if ( number < 0 )
{
a[--negative_begin] = number;
}
else
{
a[positive_end++] = number;
}
}
if ( positive_end != 0 && negative_begin != N )
{
for ( size_t i = 0; i < positive_end; i++ )
{
size_t j = negative_begin;
while ( j != N && a[i] + a[j] != 0 ) ++j;
if ( j != N ) std::cout << a[i] << '\t' << a[j] << std::endl;
}
}
return 0;
}
If for example to enter the following sequence of numbers
1 2 -3 4 -5 6 7 3 -9 9 101
then the output will be
3 -3
9 -9
Also you could sort each part of the array (the part of positive numbers and the part of negative numbers) and apply standard algorithm std::set_intersection. In this case you could exclude situations when one negative number corresponds to several positive numbers.:)
You did not pay enough attention to the logic of your code. I'll assume you are very new at this, but no person will want to enter 100 inputs before they see what your program does.
Here is what's wrong with your code:
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i; // OK
int myArray[100]; // OK, an array with 100 elements
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){ //this is where you got it wrong
// this should have been nCounter instead of number
// If you are looking at 100 elements then the condition
// should be "nCounter != 100"
cin >> number;
myArray[0]= number; // this should have been "myArray [nCounter]=number;"
nCounter += 1;
}
for ( i = 0; i <= nCounter; i++ ){ // defining i from outer scope is unnecessary
// since it is only used in the for loop
if (myArray[i] > 0) // I'm stuck at here! // Put a semicolon here
// the remainder of the code probably here
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
//initialize size and empty array
int size = 10, x;
int myArray[10] = {};
//enter integers into array
for (int i = 0; i < size; i++)
{
cin >> myArray[i];
}
//search array for negative numbers
for (int i = 0; i < size; i++)
{
if (myArray[i] < 0)
{
x = (myArray[i] * (-1)); //multiply by -1 to get (+)
cout << x << ' ';
}
}
return 0;
}

No repeating digits and reconstructing int

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

How do I split an int into its digits?

How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.
Given the number 12345 :
5 is 12345 % 10
4 is 12345 / 10 % 10
3 is 12345 / 100 % 10
2 is 12345 / 1000 % 10
1 is 12345 / 10000 % 10
I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.
Reversed order digit extractor (eg. for 23 will be 3 and 2):
while (number > 0)
{
int digit = number%10;
number /= 10;
//print digit
}
Normal order digit extractor (eg. for 23 will be 2 and 3):
std::stack<int> sd;
while (number > 0)
{
int digit = number%10;
number /= 10;
sd.push(digit);
}
while (!sd.empty())
{
int digit = sd.top();
sd.pop();
//print digit
}
The following will do the trick
void splitNumber(std::list<int>& digits, int number) {
if (0 == number) {
digits.push_back(0);
} else {
while (number != 0) {
int last = number % 10;
digits.push_front(last);
number = (number - last) / 10;
}
}
}
A simple answer to this question can be:
Read A Number "n" From The User.
Using While Loop Make Sure Its Not Zero.
Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
Then Divide The Number "n" By 10..This Removes The Last Digit of Number
"n" since in int decimal part is omitted.
Display Out The Number.
I Think It Will Help. I Used Simple Code Like:
#include <iostream>
using namespace std;
int main()
{int n,r;
cout<<"Enter Your Number:";
cin>>n;
while(n!=0)
{
r=n%10;
n=n/10;
cout<<r;
}
cout<<endl;
system("PAUSE");
return 0;
}
cast it to a string or char[] and loop on it
the classic trick is to use modulo 10:
x%10 gives you the first digit(ie the units digit). For others, you'll need to divide first(as shown by many other posts already)
Here's a little function to get all the digits into a vector(which is what you seem to want to do):
using namespace std;
vector<int> digits(int x){
vector<int> returnValue;
while(x>=10){
returnValue.push_back(x%10);//take digit
x=x/10; //or x/=10 if you like brevity
}
//don't forget the last digit!
returnValue.push_back(x);
return returnValue;
}
Declare an Array and store Individual digits to the array like this
int num, temp, digits = 0, s, td=1;
int d[10];
cout << "Enter the Number: ";
cin >> num;
temp = num;
do{
++digits;
temp /= 10;
} while (temp);
for (int i = 0; i < digits-1; i++)
{
td *= 10;
}
s = num;
for (int i = 0; i < digits; i++)
{
d[i] = s / td %10;
td /= 10;
}
int n = 1234;
std::string nstr = std::to_string(n);
std::cout << nstr[0]; // nstr[0] -> 1
I think this is the easiest way.
We need to use std::to_string() function to convert our int to string so it will automatically create the array with our digits. We can access them simply using index - nstr[0] will show 1;
Start with the highest power of ten that fits into an int on your platform (for 32 bit int: 1.000.000.000) and perform an integer division by it. The result is the leftmost digit. Subtract this result multipled with the divisor from the original number, then continue the same game with the next lower power of ten and iterate until you reach 1.
You can just use a sequence of x/10.0f and std::floor operations to have "math approach".
Or you can also use boost::lexical_cast(the_number) to obtain a string and then you can simply do the_string.c_str()[i] to access the individual characters (the "string approach").
I don't necessarily recommend this (it's more efficient to work with the number rather than converting it to a string), but it's easy and it works :)
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <boost/lexical_cast.hpp>
int main()
{
int n = 23984;
std::string s = boost::lexical_cast<std::string>(n);
std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout, "\n"));
return 0;
}
int n;//say 12345
string s;
scanf("%d",&n);
sprintf(s,"%5d",n);
Now you can access each digit via s[0], s[1], etc
You can count how many digits you want to print first
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int number, result, counter=0, zeros;
do{
cout << "Introduce un numero entero: ";
cin >> number;
}while (number < 0);
// We count how many digits we are going print
for(int i = number; i > 0; i = i/10)
counter++;
while(number > 0){
zeros = pow(10, counter - 1);
result = number / zeros;
number = number % zeros;
counter--;
//Muestra resultados
cout << " " << result;
}
cout<<endl;
}
Based on icecrime's answer I wrote this function
std::vector<int> intToDigits(int num_)
{
std::vector<int> ret;
string iStr = to_string(num_);
for (int i = iStr.size() - 1; i >= 0; --i)
{
int units = pow(10, i);
int digit = num_ / units % 10;
ret.push_back(digit);
}
return ret;
}
int power(int n, int b) {
int number;
number = pow(n, b);
return number;
}
void NumberOfDigits() {
int n, a;
printf("Eneter number \n");
scanf_s("%d", &n);
int i = 0;
do{
i++;
} while (n / pow(10, i) > 1);
printf("Number of digits is: \t %d \n", i);
for (int j = i-1; j >= 0; j--) {
a = n / power(10, j) % 10;
printf("%d \n", a);
}
}
int main(void) {
NumberOfDigits();
}
#include <iostream>
using namespace std;
int main()
{
int n1 ;
cout <<"Please enter five digits number: ";
cin >> n1;
cout << n1 / 10000 % 10 << " ";
cout << n1 / 1000 % 10 << " ";
cout << n1 / 100 % 10 << " ";
cout << n1 / 10 % 10 << " ";
cout << n1 % 10 << " :)";
cout << endl;
return 0;
}