how can i remove all digits before some specific digit - c++

How can i remove all digits from number before finding specific digit.
Let's say i want to get all digits after digit 1 (1-included)
Example: 3543125 - i want to get digits 125
i started doing this:
int n, result;
cout << "Please enter number: ";
cin >> n;
while (n>0)
{
n = n % 10;
}
to get last digit, but i don't know how you can save it in variable and then add the second digit to it.
Can someone please explain, how can i solve this?

Here is an algorithm I didn't test it but it works {only with loops and if}
int num = 3543125;
int temp = 0;
do //get the result in reverse number
{
temp += num % 10;
temp *= 10;
num /= 10;
if (num % 10 == 1)
temp += 1;
} while (num % 10 != 1);
int result = 0;
while (temp > 0) //reverse the temp number to result
{
result = result * 10 + (temp % 10);
temp = temp / 10;
}
cout << result; // = 125

Try this one. (too simple :-) )
#include <math.h>
int n,a, result=0;
cout << "Please enter number: ";
cin >> n;
cout << "Please enter number of digits: ";
cin >> a;
int b=a;
while(b>0) {
result += n%10 * pow(10,a-b--);
n=n%10;
}
std::cout<<"result: "<<result;

Related

I am not getting desired output in reverse a number code in C++

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

Why C++ doesn't take correct value in a loop?

I'm trying to find prime numbers and for that I do:
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int count;
cin >> count;
for(int i = 0; i < count; i++) {
int num, num2;
cin >> num;
num2 = num;
int res = 1;
while(num > 1) {
for(int j = 2; j < static_cast<int>(sqrt(num) + 0.5); j++) {
int a = num2 % j;
if(a == 0) {
res = res * j;
num2 = num2 / j;
//cout << j << endl;
}
}
}
cout << "Result is: " << res << endl;
}
return 0;
}
but I do not know why, when I enter 315 it prints me: 3 5 3, without 7. But when I paste 17 instead of static_cast<int>(sqrt(num) - 0.5) that gives me 17, too, it prints the 7, as well.
So, what is the problem, that when I type 17 it prints me 7, but when I calculate with sqrt - it doesn't?
Also, it does not print this one cout << "Result is: " << res << endl;.
I did not work with C++ for a long time, so may be I forgot something?
This program attempts to factor a number. Whenever the number hits 1, it has been fully factorized. So the loop should be while (num>1).
Furthermore, you fail to extract powers of primes. You will get 2 and 4 if num is 8. This is solvable if you replace the "int a=num%j;if(a==0)" lines with while (num % j == 0). You'd get the same prime repeatedly, sure [that can be fixed too if you wish].
Alright, I have actually introduced an important performance problem to gain correctness. But can we regain the performance?
You can add an additional condition in the for loop: if (j * j > num) {cout<<num; num=1;}
In the comments, the OP says he wants to obtain all prime factors and ... multiply them together? I'll write code that handles one number below:
int num, res = 1;
cin >> num;
for (int d = 2; d <= num; d++)
{
while(num % d == 0) //while also acts as if
{
cout << d << " ";
num = num / d; //or num /= d;
res = res * d; //or res *= d;
}
}
//here num is 1, res is the original number and the prime factors have been printed
static_cast<int>(sqrt(315) - 0.5) is equal to 17, but you are probably dividing num by some j on the previous iteration of the for loop, here:
num = num / j;

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++ Programming help

You create a program that displays the sum of even integers between and including two numbers entered by the user ..
ex) 2 and 7 = the sum of 12 (2+4+6)
this is what i have so far! butt if u can just put me in the right direction that would be helpful
//Advanced30.cpp - displays the sum of the even integers between and
//including two numbers entered by the user
//Created/revised by <your name> on <current date>
#include <iostream>
using namespace std;
int main()
{
// declare variables
int num1 = 0;
int num2 = 0;
int sum= 0;
cout << "Enter the First Number:" << endl;
cin >> num1;
cout << "Enter the Second Number:" << endl;
cin >> num2;
if ( num1 > num2)
{
cout << "Invalid entry. Final number must be less than the first number. Please try again." << endl;
}
for ( int sum = (((num1 + 1)/2)*2); num1 <= (((num2 + 1)/2)*2) ; sum = 2 + (((num1 + 1)/2)*2) )
return 0;
} //end of main function
In your for loop it should be like this.
double sum = 0.0;
for(i = num1; i <= num2; i++){
if(i % 2 == 0){ // Is our number even
sum += i;
}
}
That's it and it print out sum.
I would simplify your for loop
for(int i = num1; i <= num2; i++) {
if(i % 2 == 0) sum += i;
}
This will look at twice as many numbers, but honestly that's not all that much more expensive.
You could also do it in O(1) time by taking advantage of the fact that the sum 1..n == n*(n+1)
Here's a very simple example in Java, translating it to C++ won't be too difficult I hope :) no C++ compiler on this machine :-X
import java.util.*;
class DoubleSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int low = (num1 - 1)/ 2;
int high = num2 / 2;
int sumLow = (low*(low + 1));
int sumHigh = (high*(high + 1));
int sum = sumHigh - sumLow;
System.out.println(sum);
}
}
You are using the same variable to control the for loop and to the sum, this won't work. Try this:
int even1 = num1 % 2 == 0 ? num1 : num1+1;
int even2 = num2 % 2 == 0 ? num2 : num2-1;
for (int i = even1; i <= even2; i += 2) sum += i;
Note that you don't really need a for loop:
int even1 = num1 % 2 == 0 ? num1 : num1+1;
int even2 = num2 % 2 == 0 ? num2 : num2-1;
// how many numbers you will sum (remember they are even, so we need to divide by 2)
int count = 1 + (even2 - even1)/2;
sum = (even1 + even2) * (count/2);
if (count % 2 == 1) sum += (even1 + even2)/2;
for(int i = num1; i <= num2; i++)
{
if(!(i & 1))
sum += i;
}
Your code would end up in an infinite loop.
Look at the for() loop. You have the condition
num1 <= (((num2 + 1)/2)*2)
to determine whether your loop terminates. However, since num1 itself is never incremented, and num1 < num2 is guaranteed, this condition will always be true - which means your for loop would never end. I would also suggest using a separate looping variable.

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