Reverse of a number with leading zeroes - c++

How do we reverse a number with leading zeroes in number ?
For ex: If input is 004,
output should be 400.
I wrote below program but it works only when no leading zeroes in input.
int num;
cout<<"Enter number "<<endl;
cin>>num;
int rev = 0;
int reminder;
while(num != 0)
{
reminder = num % 10;
rev = rev * 10 + reminder;
num = num / 10;
}
cout<<"Reverse = "<<rev<<endl;
Is there any way to input a number with leading zeroes ? Even then, Above logic doesn't work for such numbers.
Any simple solution ? It is doable by taking input as string and processing it. But that doesn't look nice.
*EDIT: If length of number is known, it looks to be possible to reverse a number with leading zeroes. (Without using string)*
I shall post the code as soon as it works.
EDIT 2: I tried to put back characters to cin stream and then read and calculate the reverse. It is working for 2 digit numbers.
But if length is known, its far easier to find reverse. All i need to do is, multiply by 10 for required number of times.
So i think, i would go with string approach.
Hoping that interviewer would be happy :)

Leading zeroes are not represented by binary numbers (int, double, etc.) So you'll probably have to use std::string. Read the input into the string, then call std::reverse() passing the string as input.

Yes, you must use a string. You cannot store leading zeros in an int.

If you know the total width you'd like the number to be before-hand, you can reuse the code you have and store the results (from right to left) in a zero initialized array. Note: you'd probably want to add some error checking to the code listed below.
int num, width;
cout<<"Enter number "<<endl;
cin>>num;
cout<<"Enter width: "<<endl;
cin>>width;
int rev[width];
for (int i = 0; i < width; ++i)
rev[i] = 0;
int cnt = width - 1;
int rev = 0;
int reminder;
while(num != 0)
{
reminder = num % 10;
// rev = rev * 10 + reminder;
rev[cnt] = remainder;
--cnt;
num = num / 10;
}
cout << "Reverse: ";
for (int i = 0; i < width; ++i)
cout << rev[i];
cout << endl;
This will allow you to manipulate the number more easily in the future as well.

Read the number in string format (that is, use std::string) and reverse the string.

Once you convert your input to an integer, which you do in line 3, any information about the leading zeroes in the input of the user is lost.
You'll have to use a string.

A recursive approach, but easily converted to a loop...
#include <iostream>
int f(int value = 1)
{
char c;
return (std::cin.get(c) && isdigit(c))
? (c - '0') * value + f(10 * value)
: 0;
}
int main()
{
std::cout << f() << '\n';
}

As ChrisF said, you need to load a string, because 4 and 004 is the same int and you cannot distinguish it after you assign it to an int variable.
The next thing to do is trim the string to contain just digits (if you want to be correct) and run std::reverse on it - and you're done.

Keep the number as a string, and use std::reverse.
std::string num;
std::cout << "Enter number " << std::endl;
std::cin >> num;
std::string rev(num);
std::reverse(rev.begin(), rev.end());
std::cout << "Reverse = " << rev << std::endl;

Replace your while loop with a for loop with the same number of runs as you wish the original number has digits (including leading zeros). e.g. 004 would require the loop to be run 3 times, and not to terminate prematurely once x == 0.

s = int(raw_input(" enter the no of tyms :"))
n = 0
list, list1 = [], []
while n <= s:
m = raw_input("enter the number:")
n=n+1
list.append(m)
print list
list.reverse()
print list
Reverse in one of the best lang Python.

Related

How can you get a "x" element from rand()?

I have a rand number generator.
Now my question is how do I get for instance the first/second/third/fourth digit of the generated random number.
Implementing this so the user can use a hint when guessing the number.
example: result(rand): 9876
print hint 1: second number 8
print hint 2: fourth number 6
Whats the best way to tackle this? I've been thinking to convert the string to an char array in order to print out the certain locations where the values are being kept but that won't work I guess.
Correct me if my way of asking this questions is very bold.
int nummer = 4;
std :: string result = "";
for (int i = 0; i < nummer; i++)
{
result.push_back(rand()%10 + '0');
}
You have two options for solving this problem:
Create one random number between 0 and 9999 and then calculate the individual digits.
Create four random numbers between 0 and 9 which represent the individual digits and then, if necessary, calculate the whole number from the individual digits.
Normally, doing option #1 would be more straightforward. You seem to be going for option #2. Both ways are possible and which one is better probably depends on whether your program works more with the number as a whole or with individual digits.
If you decide to do option #2, then the question arises whether you want to work with ASCII character codes between '0' and '9' (i.e. codes between 48 and 57) or with actual numbers between 0 and 9. Normally, it is a bit easier to work with the actual numbers instead of ASCII character codes, but both ways are feasible.
Personally, I would solve it the following way:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
//seed random number generator
std::srand( std::time(nullptr) );
//note that NUM_DIGITS should not be set so high
//that MAX_NUMBER is not representable as an `int`
constexpr int NUM_DIGITS = 4;
//set this to the highest possible number that
//corresponds to NUM_DIGITS
constexpr int MAX_NUMBER = 9999;
//this variable holds the entire number
int random;
//this array holds the individual digits
int digits[NUM_DIGITS];
///generate the random number
random = std::rand()%(MAX_NUMBER+1);
//calculate the individual digits of the random number
int remaining = random;
int divisor = (MAX_NUMBER+1) / 10;
for ( int i = 0; i < NUM_DIGITS; i++ )
{
digits[i] = remaining / divisor;
remaining = remaining % divisor;
divisor/= 10;
}
//print the whole random number
std::cout << "Whole random number:\n" << random << "\n\n";
//print the individual digits
std::cout << "Individual digits:\n";
for ( int i = 0; i < NUM_DIGITS; i++ )
{
std::cout << digits[i] << "\n";
}
}
Sample output (actual output depends on random number seed):
Whole random number:
8695
Individual digits:
8
6
9
5
I've been thinking to convert the string to an char array but that won't work I guess.
I see no reason to do this. In your posted code, you can simply write
result[0]
result[1]
result[2]
result[3]
to access the individual digits of the number.
In that respect, converting a std::string to a C-style character array has no advantages.
The code you've written is fine.
Whether you store the characters in an array or a string, you can access the elements using result[i] where i starts at 0.
I've been thinking to convert the string to an char array but that won't work I guess.
Using std::string is usually a better idea - still possible but a little harder to screw them up, and they're more powerful generally, but you could use a char array if you wanted:
char result[] = "0000"; // will have null terminator
for (int i = 0; i < 4; ++i)
result[i] = rand() % 10 + '0';
Letting result be a 5-character array - with a null terminator - means you can still print all four digits easily with std::cout << result.
Alternatively, you could pick a random 4-digit number and convert it to a string of a particular width, using '0's to pad:
#include <iostream>
#include <iomanip>
int main() {
std::ostringstream oss;
oss << std::setw(4) << std::setfill('0') << rand() % 10000;
std::cout << '[' << oss.str() << "]\n";
}

Convert number in binary and print out as matrix (C++)

Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific.
I am writing a code that takes a user input between 0 and 511 and converts it into a binary number. Then the program will replace all the 1's in the binary number with T and all the 0's in the number as H. Afterwards it will print out the results (the binary number with the H and T replacement) as a 3*3 matrix.
This is the desired output (not what I have but what I want):
Enter a number between 0 and 511: 299
The binary number is: 100101011
The matrix is:
THH
THT
HTT
The problem with my code is that I am unsure of how to replace an array that consists of all integers to have certain parts of the index to be either characters or strings. For sure the part with the binary number conversion works but the replacement of the 0's and 1's of the array is where the trouble is at. I am also unsure of how to print out the matrix result. I assume it goes either of 2 ways: 1. The program creates a new array for the previous array's elements stored and prints out the matrix array instead. 2. There is a way to only print the array 3 lines at a time. The only way I can think of is to somehow cut the for loop short and add a line break after every 3 values. I am aware that there are a few pointable errors in my code but I do not know how to fix them.
Although this is in the C++ language, what I have learned is the C style syntax (no std:: kinds of code or stuff like that because I haven't learned it yet and I will not understand it) So far I have learned basic arrays, loops, and functions.
#include <iostream>
using namespace std;
int main(){
int arr[10];
int input, i;
cout<<"Enter a number between 0 and 511: ";
cin>> input;
for(i = 0; input > 0; i++){
arr[i] = (input % 2);
input = input / 2;
}
cout<<"The binary number is: ";
for(i = i - 1; i >= 0; i--){
cout<<arr[i];
}
string newArr[10] = arr[10]; //the error here states that the array initializer must be an initializer list
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
if(arr[i] == 1){
arr[i] = "T"; //the error here mentions that a string/ character cannot be assigned with a integer array
}
else{
arr[i] = "H";
}
}
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
cout<<arr[i]<< " ";
}
}
This would be sufficient:
#include <iostream>
using namespace std;
int main()
{
// you never actually checked if the input is valid
// so you may or may not want this loop:
int input;
do
{
cout << "Enter a number between 0 and 511: ";
cin >> input;
} while ((input < 0) || (input > 511));
// space for matrix, new lines and null
// to construct a null terminated string
char buffer[3 * (3 + 1) + 1];
int i = 0;
// since the bits are read from left to right
// I will use a mask instead of bit shifting the input
int bit = 1 << 9;// 2^9 == 512
for (int r = 0; r < 3; r++)// rows
{
for (int c = 0; c < 3; c++)// columns
{
// this could come after the check
// and then bit would start at 256
bit >>= 1;
// perform the check and add the corresponding letter
buffer[i++] = (bit & input) ? 'T' : 'H';
}
// add new lines
buffer[i++] = '\n';
}
// if you don't want the last '\n'
// this could be { buffer[--i] = '\0'; }
buffer[i++] = '\0';
cout << buffer;
}

C++ program doesn't fully execute iteration [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 4 years ago.
Improve this question
The program I've written is supposed to take in two user inputs (one being the number we're meant to check whether it's k-hyperperfect or not, the other being a maximum k-value.) if the input integer is k-hyperperfect in the range of 1 to the inputted maximum k-value, then the output should be that k-value. For example, if the input integer is 21 and the maximum k-value is 100 then the output should be 2.
My program gives the correct output for (the first number is the input integer, the second number is the k-max value, the third number is output value) ...
21 (input integer) 100 (k-max) --> 180
301 100 --> 6
12211188308281 100 --> 0
-301 100 --> 0
21 -5 --> 0
However, it doesn't correctly execute for 12211188308281 and 200 (it gives me 0 when it should give me 180). I've run my code through a step by step visualizer and it seems to just abruptly stop execution when i = 496 in the for loop within the else statement. But I don't understand why since it executes correctly for 5 other test runs.
#include <iostream>
using std::cout; using std::cin; using std::endl; using std::fixed;
int main () {
int number;
int kmax;
int sum = 0 ;
int hyper = 0;
std::cin >> number;
std::cin >> kmax;
if (number <= 6 or kmax < 1) {
std::cout << "0" << "\n";
}
else {
for (int i=1;i<=number;i++) {
if (number%i==0 and i != 1 and i != number){
sum+= i;
}
}
}
for (int k=1; k <= kmax; k++) {
hyper = ((sum)*k) + 1;
if (hyper == number) {
std::cout << k << endl;
break;
}
}
}
You need to check that numbers read through std::istreams (like std::cin) are read successfully. As the value that you enter for number is too large to store in an integer your read will fail. For example you could change your code to:
int main()
{
int number;
std::cin >> number;
if ( !std::cin )
{
std::cout << "invalid value: " << number << "\n";
return 1;
}
else
{
std::cout << "valid value: " << number << "\n";
}
// calculate answer
return 0;
}
You would then see your program printing "invalid value: 2147483647" if you have a c++11 compliant compiler or an undefined number if you have an older compiler.
Now that you have implemented reading values correctly the fix to your issue is to use a larger integer type like int64_t which is able to hold your number.
As already noted, the int type in your machine isn't big enough to store the value 12,211,188,308,281.
The C++ standard only mandates it to be capable of storing a value up to 32,767 and even in the (now common) case of a 32-bit int or long int), the limit would be 2,147,483,647. So you need a long long int or an int64_t (if it's present in your implementation).
A simple check like
if (std::cin >> number >> kmax ) { // perform calculations...
Would have shown the error sooner.
That beeing said, there are also some simple changes that could be done to the posted code in order to make it more efficient. The first loop can be optimized considering the "symmetry" of the divisors of a given number: meaning, if n is divisible by a, so that b = n/a is a whole number, b too is a divisor of n. This will limit the number of iterations to the square root of n, instead of n.
long long int number,
kmax,
sum = 0;
// ...
long long int temp = number,
i = 2;
for (; i * i < number; i++) {
if (number % i == 0) {
temp = number / i;
sum += i + temp;
}
}
if (i * i == number) {
sum += i;
}
There probably are better algorithms, but I'm unfamiliar with those.
The second loop, in my opinion, is unnecessary. The value k can be calculated directly:
if ( (number - 1) % sum == 0) {
std::cout << (number - 1) / sum << '\n';
}
You are assigning a too long value 12211188308281 to integer "number", which can't contain it fully and it is getting truncated to 596285753. You can add a print statement to print it.
std::cout<<number;
which will print 596285753.
As suggested you should use long long int. Again its dependent on the software platform running on your system.

C++ Program abruptly ends after cin

I am writing code to get the last digit of very large fibonacci numbers such as fib(239), etc.. I am using strings to store the numbers, grabbing the individual chars from end to beginning and then converting them to int and than storing the values back into another string. I have not been able to test what I have written because my program keeps abruptly closing after the std::cin >> n; line.
Here is what I have so far.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using namespace std;
char get_fibonacci_last_digit_naive(int n) {
cout << "in func";
if (n <= 1)
return (char)n;
string previous= "0";
string current= "1";
for (int i = 0; i < n - 1; ++i) {
//long long tmp_previous = previous;
string tmp_previous= previous;
previous = current;
//current = tmp_previous + current; // could also use previous instead of current
// for with the current length of the longest of the two strings
//iterates from the end of the string to the front
for (int j=current.length(); j>=0; --j) {
// grab consectutive positions in the strings & convert them to integers
int t;
if (tmp_previous.at(j) == '\0')
// tmp_previous is empty use 0 instead
t=0;
else
t = stoi((string&)(tmp_previous.at(j)));
int c = stoi((string&)(current.at(j)));
// add the integers together
int valueAtJ= t+c;
// store the value into the equivalent position in current
current.at(j) = (char)(valueAtJ);
}
cout << current << ":current value";
}
return current[current.length()-1];
}
int main() {
int n;
std::cin >> n;
//char& c = get_fibonacci_last_digit_naive(n); // reference to a local variable returned WARNING
// http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable
cout << "before call";
char c = get_fibonacci_last_digit_naive(n);
std::cout << c << '\n';
return 0;
}
The output is consistently the same. No matter what I enter for n, the output is always the same. This is the line I used to run the code and its output.
$ g++ -pipe -O2 -std=c++14 fibonacci_last_digit.cpp -lm
$ ./a.exe
10
There is a newline after the 10 and the 10 is what I input for n.
I appreciate any help. And happy holidays!
I'm posting this because your understanding of the problem seems to be taking a backseat to the choice of solution you're attempting to deploy. This is an example of an XY Problem, a problem where the choice of solution method and problems or roadblocks with its implementation obfuscates the actual problem you're trying to solve.
You are trying to calculate the final digit of the Nth Fibonacci number, where N could be gregarious. The basic understanding of the fibonacci sequence tells you that
fib(0) = 0
fib(1) = 1
fib(n) = fib(n-1) + fib(n-2), for all n larger than 1.
The iterative solution to solving fib(N) for its value would be:
unsigned fib(unsigned n)
{
if (n <= 1)
return n;
unsigned previous = 0;
unsigned current = 1;
for (int i=1; i<n; ++i)
{
unsigned value = previous + current;
previous = current;
current = value;
}
return current;
}
which is all well and good, but will obviously overflow once N causes an overflow of the storage capabilities of our chosen data type (in the above case, unsigned on most 32bit platforms will overflow after a mere 47 iterations).
But we don't need the actual fib values for each iteration. We only need the last digit of each iteration. Well, the base-10 last-digit is easy enough to get from any unsigned value. For our example, simply replace this:
current = value;
with this:
current = value % 10;
giving us a near-identical algorithm, but one that only "remembers" the last digit on each iteration:
unsigned fib_last_digit(unsigned n)
{
if (n <= 1)
return n;
unsigned previous = 0;
unsigned current = 1;
for (int i=1; i<n; ++i)
{
unsigned value = previous + current;
previous = current;
current = value % 10; // HERE
}
return current;
}
Now current always holds the single last digit of the prior sum, whether that prior sum exceeded 10 or not really isn't relevant to us. Once we have that the next iteration can use it to calculate the sum of two single positive digits, which cannot exceed 18, and again, we only need the last digit from that for the next iteration, etc.. This continues until we iterate however many times requested, and when finished, the final answer will present itself.
Validation
We know the first 20 or so fibonacci numbers look like this, run through fib:
0:0
1:1
2:1
3:2
4:3
5:5
6:8
7:13
8:21
9:34
10:55
11:89
12:144
13:233
14:377
15:610
16:987
17:1597
18:2584
19:4181
20:6765
Here's what we get when we run the algorithm through fib_last_digit instead:
0:0
1:1
2:1
3:2
4:3
5:5
6:8
7:3
8:1
9:4
10:5
11:9
12:4
13:3
14:7
15:0
16:7
17:7
18:4
19:1
20:5
That should give you a budding sense of confidence this is likely the algorithm you seek, and you can forego the string manipulations entirely.
Running this code on a Mac I get:
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string before callin funcAbort trap: 6
The most obvious problem with the code itself is in the following line:
for (int j=current.length(); j>=0; --j) {
Reasons:
If you are doing things like current.at(j), this will crash immediately. For example, the string "blah" has length 4, but there is no character at position 4.
The length of tmp_previous may be different from current. Calling tmp_previous.at(j) will crash when you go from 8 to 13 for example.
Additionally, as others have pointed out, if the the only thing you're interested in is the last digit, you do not need to go through the trouble of looping through every digit of every number. The trick here is to only remember the last digit of previous and current, so large numbers are never a problem and you don't have to do things like stoi.
As an alternative to a previous answer would be the string addition.
I tested it with the fibonacci number of 100000 and it works fine in just a few seconds. Working only with the last digit solves your problem for even larger numbers for sure. for all of you requiring the fibonacci number as well, here an algorithm:
std::string str_add(std::string a, std::string b)
{
// http://ideone.com/o7wLTt
size_t n = max(a.size(), b.size());
if (n > a.size()) {
a = string(n-a.size(), '0') + a;
}
if (n > b.size()) {
b = string(n-b.size(), '0') + b;
}
string result(n + 1, '0');
char carry = 0;
std::transform(a.rbegin(), a.rend(), b.rbegin(), result.rbegin(), [&carry](char x, char y)
{
char z = (x - '0') + (y - '0') + carry;
if (z > 9) {
carry = 1;
z -= 10;
} else {
carry = 0;
}
return z + '0';
});
result[0] = carry + '0';
n = result.find_first_not_of("0");
if (n != string::npos) {
result = result.substr(n);
}
return result;
}
std::string str_fib(size_t i)
{
std::string n1 = "0";
std::string n2 = "1";
for (size_t idx = 0; idx < i; ++idx) {
const std::string f = str_add(n1, n2);
n1 = n2;
n2 = f;
}
return n1;
}
int main() {
const size_t i = 100000;
const std::string f = str_fib(i);
if (!f.empty()) {
std::cout << "fibonacci of " << i << " = " << f << " | last digit: " << f[f.size() - 1] << std::endl;
}
std::cin.sync(); std::cin.get();
return 0;
}
Try it with first calculating the fibonacci number and then converting the int to a std::string using std::to_string(). in the following you can extract the last digit using the [] operator on the last index.
int fib(int i)
{
int number = 1;
if (i > 2) {
number = fib(i - 1) + fib(i - 2);
}
return number;
}
int main() {
const int i = 10;
const int f = fib(i);
const std::string s = std::to_string(f);
if (!s.empty()) {
std::cout << "fibonacci of " << i << " = " << f << " | last digit: " << s[s.size() - 1] << std::endl;
}
std::cin.sync(); std::cin.get();
return 0;
}
Avoid duplicates of the using keyword using.
Also consider switching from int to long or long long when your numbers get bigger. Since the fibonacci numbers are positive, also use unsigned.

How can I seperate digits a given integer with C++?

Can you help me please? I try to do with while statement but I could not write the program.
Given an integer for example 12564897 and the program must show it 1-2-5-6-4-8-9-7
How do you detect in C++. Thanks a lot.
I tried with five digits integer.
int z,y,x,result,number1,number2,number3,number4,number5;
cout<<"Enter a five digit integer: ";
cin>>result; //read number
cout<<"The number is: "<<result<<endl;
number1 = result / 10000;
x = result / 1000;
number2 = x % 10;
y = result / 100;
number3 = y % 10;
z = result / 10;
number4 = z % 10;
number5 = result % 10;
cout<<"digits are: "<<number1<<"-"<<number2<<"-"<<number3<<"-"<<number4<<"-"<<number5<<endl;
system("pause");
return 0;
}
I think the smartest way is create a loop that divide by ten ( or the base ) and print the remainder, then divide by ten and do again. In preudo code:
let a = input
let base = 10
do
{
store a mod base in result
a = (integer) a / base;
}while(a>0)
print result reversed
mod is the remainder operator ( % in C/C++ )
please note thad by changing base you can have the digit in any representation of the number
Convert your Integer to a string and then print every character of that string with a - in between.
This is snippet from program which print out integer in reverse order.
You can modify it to fits your need (it's your homework)
//Read input number
cin >> dInput;
//Calculate log10
int logValue = (int)log10(dInput);
//Iteration through n-th power of 10
for(int i = logValue; i >= 0; i--) {
//Calculate actual power of 10
double d = pow(10,(double)i);
int n = (int)dInput / d;
//Subtract remainder from previous number
dInput -= (n * d);
//Print out "-"
cout << n;
if(i != 0) << "-";
}
I thought about writing the code itself, but since it's a homework, I'll give you the idea and let you code it
First, you'll convert that integer to a string using sprintf function
Then you'll make an integer having the size of the string. Let it be S
Then you'll make a for loop,
i=1, i < S, i+=2
i starts from 1 as the - is put after the first character
In that loop, you would insert the - character at the position of i, then you'll update integer S with the size. If you didn't update it, the following (for example) would happen
12345 (size = 5)
1-2345 (size = 5, real size = 6)
1-2-345 (size = 5, real size = 7)
It would stop here. As the condition i<5 would fail
That's all. Good luck.
OK, since everyone else has had a go, this is my attempt:
void outInt(int inInt){
int dividend;
dividend=inInt/10;
if (dividend!=0){
outInt(dividend);
cout<<"-"<<inInt%10;
}
else
cout<<(inInt);
};
No 'print result reversed' required. Should work for 0 and not print any '-' for numbers less than 10.