If we have classical decimal format in int long, we can do something like that:
const long int NUMBER = 4577;
const long int DIGIT_TO_FIND = 5;
long int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER;
long int thisDigit;
while (thisNumber != 0)
{
thisDigit = thisNumber % 10;
thisNumber = thisNumber / 10;
if (thisDigit == DIGIT_TO_FIND)
{
printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
break;
}
}
But what about binary representing or octal representing in int long?
We have:
const long int NUMBER = 01011111; // octal
const long int DIGIT_TO_FIND1 = 0;
const long int DIGIT_TO_FIND2 = 1;
Correct input:
01010101
11111111
Bad input:
02010101 (because two)
00000009 (because nine)
We need to check if int long contains only 0 or 1.
What is the simpliest way to check correct input for that? Maybe just easy question, but no idea, thank you.
To check whether a digit is a valid binary digit, compare it with 1:
if (thisDigit > 1)
{
printf("%d contains digit %d", NUMBER, thisDigit);
break;
}
As noted by #Pubby, you have an octal number instead of a decimal number, so use 8 instead of 10 to calculate digits:
thisDigit = thisNumber % 8;
thisNumber = thisNumber / 8;
If I understand your question something like this -
#include <iostream>
bool check(int number, int search_1, int search_2)
{
while(number > 0)
{
int digit = number % 10;
number = number / 10;
if (digit != search_1 && digit != search_2)
return false;
}
return true;
}
int main()
{
const int DIGIT_TO_FIND1 = 0;
const int DIGIT_TO_FIND2 = 1;
int number1 = 1001001;
std::cout << "Checking " << number1 << " : " << check(number1, DIGIT_TO_FIND1, DIGIT_TO_FIND2) <<" \n";
int number2 = 12110101;
std::cout << "Checking " << number2 << " : " << check(number2, DIGIT_TO_FIND1, DIGIT_TO_FIND2) <<" \n";
}
My solution. It's really simple.
bool check(int long number)
{
return ((number % 10 != 0) && (number % 10) != 1);
}
Related
I am trying to find a reversed number and check that it is a palindrome or not from a different approach but I was getting a right reversed number up to two digits and if the digits are more than two then I am getting wrong output. I cannot understand why is this so as I think my code is right.
below is the code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num, rem, t, add;
cin >> t;
while (t--) {
int total = 0, count = 0, i = 1, quo = 0;
cin >> num;
quo = num;
while (quo > 9) //count determiner
{
quo = quo / 10;
++count;
}
while (count >= 0) //reverse number saved in total
{
int den = pow(10, i);
rem = (num % den);
add = rem / pow(10, i - 1);
total = total + (add * pow(10, count));
++i;
--count;
}
if (total == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
please help me to know where I am going wrong in this code.
I don't understand your code. so i assumed by myself and wrote code.I assume that there will be no negative number and if there will be then i rid off negative sign. please provide desire output for negative number.
#include <iostream>
using namespace std;
int main()
{
//int num, rem, t, add;
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
int num = abs(n);
if (n < 0)
{
n = abs(n);
}
int res{ 0 };
while (n > 0)
{
res *= 10;
int rem = n % 10;
res += rem;
n /= 10;
}
if (res == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
ouptut of above code:
4
-191
Palindrome
232
Palindrome
123
Not a Palindrome
561
Not a Palindrome
Your code to reverse a number is very convoluted, as it uses pow (a floating point function) to get each digit. This is totally unnecessary if you look for the pattern of how to reverse an integer.
Simple addition, multiplying by 10, and modulus is all that's necessary to do this. Note that I created a function, so that it is easy to follow:
#include <cmath>
#include <iostream>
int reverse_int(int num)
{
int total = 0;
// take care of negative by using absolute value
int tempNum = abs(num);
while (tempNum > 0)
{
total = (total*10) + (tempNum % 10);
tempNum /= 10;
}
return (num < 0)?-total:total;
}
int main()
{
int num = 1234321;
if ( num == reverse_int(num))
std::cout << num << " is a palindrome\n";
else
std::cout << num << " is not a palindrome\n";
int num2 = 123;
if ( num2 == reverse_int(num2))
std::cout << num2 << " is a palindrome\n";
else
std::cout << num2 << " is not a palindrome\n";
}
Output:
1234321 is a palindrome
123 is not a palindrome
The loop is very simple if you follow what is going on:
number = 123 (Assume this is our number)
total = 0;
Loop while (number > 0):
First iteration:
total = (total * 10) + (number % 10) --> (0 * 10) + (0 % 3) --> 3
number /= 10 --> 12
Second iteration:
total = (total * 10) + (number % 10) = (3 * 10) + (12 % 10) --> 32
number /= 10 --> 1
Third iteration:
total = (total * 10) + (number % 10) = (32 * 10) + (1 % 10) --> 321
number /= 10 --> 0 (Stop the loop)
total = 321
At the end of the function, we just return the value, and make it negative if the original number was negative.
You are not checking if the input was valid. So if we leave that aside and assume the input is a valid integer then you can use a std::string and reverse it via std::reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::string reverse = input;
std::reverse(reverse.begin(),reverse.end());
if (input == reverse) std::cout << "Palindrome number"
}
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
I've just recently started to dabble in coding, and I ran into a problem that I haven't been able to solve for days, and the closest thing I've been able to find online is a program checking whether a number contains a specific digit, but that doesn't really apply in my case, I don't think. The problem is to let the user enter two positive numbers and check whether the reverse of the second number is contained within the first one. For example if you enter 654321 and 345, it would say say that it contains it because the reverse of 345 is 543 and 654321 contains that. Here's what I've been trying, but it has been a disaster.
P.S: The variables should stay integer through the program.
#include <iostream>
using namespace std;
bool check(int longer, int shorter)
{
int i = 1;
int rev=0;
int digit;
while (shorter > 0)
{
digit = shorter%10;
rev = rev*10 + digit;
shorter = shorter/10;
}
cout << rev << endl;
bool win=0;
int left = longer / 10; //54321
int right = longer % 10; // 65432
int middle = (longer /10)%10; // 5432
int middle1;
int middle2;
int trueorfalse = 0;
while (left > 0 && right > 0 && middle1 > 0 && middle2 >0)
{
left = longer / 10; //4321 //321
right = longer % 10; //6543 //654
middle1 = middle%10; //543
middle2= middle/10; //432
if (rev == left || rev == right || rev == middle1 || rev == middle2 || rev == middle)
{
win = true;
}
else
{
win = false;
}
}
return win;
}
int main ()
{
int longer;
int shorter;
int winorno;
cout << "Please enter two numbers, first of which is longer: ";
cin >> longer;
cin >> shorter;
winorno = check(longer,shorter);
if (winorno==true)
{
cout << "It works.";
}
else
{
cout << "It doesn't work.";
}
return 0;
}
The more you overthink the plumbing, the easier it is to
stop up the drain. -- Scotty, Star Trek III.
This becomes much easier if you divide this task in two parts:
Reverse the digits in an integer.
Search the second integer for the reversed integer calculated by the first part.
For the first part, assume that n contains the number to reverse.
int modulo=1;
int reversed_n=0;
do
{
reversed_n = reversed_n * 10 + (n % 10);
modulo *= 10;
} while ( (n /= 10) != 0);
The end result is if n contained 345, reversed_n will end up with 543, and modulo will be 1000. We'll need modulo for the second part.
The reason the loop is structured this way is intentional. If the original number is 0, we want to wind up with reversed_n also 0, and modulo as 10.
And now, we can take a similar approach to search the second number, called search, whether it contains reversed_n:
for (;;)
{
if ((search % modulo) == reversed_n)
{
std::cout << "Yes" << std::endl;
return 0;
}
if (search < modulo)
break;
search /= 10;
}
std::cout << "No" << std::endl;
Complete program:
#include <iostream>
int main()
{
int search=654321;
int n=345;
int modulo=1;
int reversed_n=0;
do
{
reversed_n = reversed_n * 10 + (n % 10);
modulo *= 10;
} while ( (n /= 10) != 0);
for (;;)
{
if ((search % modulo) == reversed_n)
{
std::cout << "Yes" << std::endl;
return 0;
}
if (search < modulo)
break;
search /= 10;
}
std::cout << "No" << std::endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int calculateNumLength(int num){
int length = 0;
while (num > 0) {
num = num / 10;
length++;
}
return length;
}
bool check(int longer, int shorter){
int reversed = 0;
int digit;
int shortLength = calculateNumLength(shorter);
int longLength = calculateNumLength(longer);
int diffrence = longLength - shortLength;
int possibleValues = diffrence + 1;
int possibleNums[possibleValues];
while ( shorter > 0 ) {
digit = shorter % 10;
rev = ( rev * 10 ) + digit;
shorter = shorter / 10;
}
int backstrip = pow(10, diffrence);
int frontstrip = pow(10, longLength-1);
int arrayCounter = 0;
while ( longer > 0 ){
possibleNums[arrayCounter++] = longer/backstrip;
if ( backstrip >= 10 ){
backstrip = backstrip / 10;
}else{
break;
}
longer = longer % frontstrip;
frontstrip = frontstrip / 10;
}
for (int i=0;i<possibleValues;i++){
if (possibleNums[i] == rev ){
return true;
}
}
return false;
}
int main() {
std::cout << check(654321,123) << std::endl;
return 0;
}
I am trying to write a code that takes a binary number input as a string and will only accept 1's or 0's if not there should be an error message displayed. Then it should go through a loop digit by digit to convert the binary number as a string to decimal. I cant seem to get it right I have the fact that it will only accept 1's or 0's correct. But then when it gets into the calculations something messes up and I cant seem to get it correct. Currently this is the closest I believe I have to getting it working. could anyone give me a hint or help me with what i am doing wrong?
#include <iostream>
#include <string>
using namespace std;
string a;
int input();
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] = '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + pow(x,2);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
int input()
{
int x, x2, count, repeat = 0;
while (repeat == 0)
{
cout << "Enter a string representing a binary number => ";
cin >> a;
count = a.length();
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
cout << a << " is not a string representing a binary number>" << endl;
repeat = 0;
break;
}
else
repeat = 1;
}
}
return 0;
}
I don't think that pow suits for integer calculation. In this case, you can use shift operator.
a[i] = '1' sets the value of a[i] to '1' and return '1', which is always true.
You shouldn't access a[length], which should be meaningless.
fixed code:
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length - 1; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] == '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + (1 << x);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
I would use this approach...
#include <iostream>
using namespace std;
int main()
{
string str{ "10110011" }; // max length can be sizeof(int) X 8
int dec = 0, mask = 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str[i] == '1') {
dec |= mask;
}
mask <<= 1;
}
cout << "Decimal number is: " << dec;
// system("pause");
return 0;
}
Works for binary strings up to 32 bits. Swap out integer for long to get 64 bits.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string getBinaryString(int value, unsigned int length, bool reverse) {
string output = string(length, '0');
if (!reverse) {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << i)) != 0) {
output[i] = '1';
}
}
}
else {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << (length - i - 1))) != 0) {
output[i] = '1';
}
}
}
return output;
}
unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
unsigned long val = 0;
unsigned int offset = 0;
if (lsbindex > msbindex) {
size_t length = lsbindex - msbindex;
for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << (length - offset));
}
}
}
else { //lsbindex < msbindex
for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << offset);
}
}
}
return val;
}
int main() {
int value = 23;
cout << value << ": " << getBinaryString(value, 5, false) << endl;
string str = "01011";
cout << str << ": " << getInteger(str, 1, 3) << endl;
}
I see multiple misstages in your code.
Your for-loop should start at i = length - 1 instead of i = length.
a[i] = '1' sets a[i] to '1' and does not compare it.
pow(x,2) means and not . pow is also not designed for integer operations. Use 2*2*... or 1<<e instead.
Also there are shorter ways to achieve it. Here is a example how I would do it:
std::size_t fromBinaryString(const std::string &str)
{
std::size_t result = 0;
for (std::size_t i = 0; i < str.size(); ++i)
{
// '0' - '0' == 0 and '1' - '0' == 1.
// If you don't want to assume that, you can use if or switch
result = (result << 1) + str[i] - '0';
}
return result;
}
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 );
}