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.
Related
I am new to competitive programming. I recently gave the Div 3 contest codeforces. Eventhough I solved the problem C, I really found this code from one of the top programmers really interesting. I have been trying to really understand his code, but it seems like I am too much of a beginner to understand it without someone else explaining it to me.
Here is the code.
void main(){
int S;
cin >> S;
int ans = 1e9;
for (int mask = 0; mask < 1 << 9; mask++) {
int sum = 0;
string num;
for (int i = 0; i < 9; i++)
if (mask >> i & 1) {
sum += i + 1;
num += char('0' + (i + 1));
}
if (sum != S)
continue;
ans = min(ans, stoi(num));
}
cout << ans << '\n';
}
The problem is to find the minimum number whose sum of digits is equal to given number S, such that every digit in the result is unique.
Eq. S = 20,
Ans = 389 (3+8+9 = 20)
Mask is 9-bits long, each bit represents a digit from 1-9. Thus it counts from 0 and stops at 512. Each value in that number corresponds to possible solution. Find every solution that sums to the proper value, and remember the smallest one of them.
For example, if mask is 235, in binary it is
011101011 // bit representation of 235
987654321 // corresponding digit
==> 124678 // number for this example: "digits" with a 1-bit above
// and with lowest digits to the left
There are a few observations:
you want the smallest digits in the most significant places in the result, so a 1 will always come before any larger digit.
there is no need for a zero in the answer; it doesn't affect the sum and only makes the result larger
This loop converts the bits into the corresponding digit, and applies that digit to the sum and to the "num" which is what it'll print for output.
for (int i = 0; i < 9; i++)
if (mask >> i & 1) { // check bit i in the mask
sum += i + 1; // numeric sum
num += char('0' + (i + 1)); // output as a string
}
(mask >> i) ensures the ith bit is now shifted to the first place, and then & 1 removes every bit except the first one. The result is either 0 or 1, and it's the value of the ith bit.
The num could have been accumulated in an int instead of a string (initialized to 0, then for each digit: multiply by 10, then add the digit), which is more efficient, but they didn't.
The way to understand what a snippet of code is doing is to A) understand what it does at a macro-level, which you have done and B) go through each line and understand what it does, then C) work your way backward and forward from what you know, gaining progress a bit at a time. Let me show you what I mean using your example.
Let's start by seeing, broadly (top-down) what the code is doing:
void main(){
// Set up some initial state
int S;
cin >> S;
int ans = 1e9;
// Create a mask, that's neat, we'll look at this later.
for (int mask = 0; mask < 1 << 9; mask++) {
// Loop state
int sum = 0;
string num;
// This loop seems to come up with candidate sums, somehow.
for (int i = 0; i < 9; i++)
if (mask >> i & 1) {
sum += i + 1;
num += char('0' + (i + 1));
}
// Stop if the sum we've found isn't the target
if (sum != S)
continue;
// Keep track of the smallest value we've seen so far
ans = min(ans, stoi(num));
}
// Print out the smallest value
cout << ans << '\n';
}
So, going from what we knew about the function at a macro level, we've found that there are really only two spots that are obscure, the two loops. (If anything outside of those are confusing to you, please clarify.)
So now let's try going bottom-up, line-by-line those loops.
// The number 9 appears often, it's probably meant to represent the digits 1-9
// The syntax 1 << 9 means 1 bitshifted 9 times.
// Each bitshift is a multiplication by 2.
// So this is equal to 1 * (2^9) or 512.
// Mask will be 9 bits long, and each combination of bits will be covered.
for (int mask = 0; mask < 1 << 9; mask++) {
// Here's that number 9 again.
// This time, we're looping from 0 to 8.
for (int i = 0; i < 9; i++) {
// The syntax mask >> i shifts mask down by i bits.
// This is like dividing mask by 2^i.
// The syntax & 1 means get just the lowest bit.
// Together, this returns true if mask's ith bit is 1, false if it's 0.
if (mask >> i & 1) {
// sum is the value of summing the digits together
// So the mask seems to be telling us which digits to use.
sum += i + 1;
// num is the string representation of the number whose sum we're finding.
// '0'+(i+1) is a way to convert numbers 1-9 into characters '1'-'9'.
num += char('0' + (i + 1));
}
}
}
Now we know what the code is doing, but it's hard to figure out. Now we have to meet in the middle - combine our overall understanding of what the code does with the low-level understanding of the specific lines of code.
We know that this code gives up after 9 digits. Why? Because there are only 9 unique non-zero values (1,2,3,4,5,6,7,8,9). The problem said they have to be unique.
Where's zero? Zero doesn't contribute. A number like 209 will always be smaller than its counterpart without the zero, 92 or 29. So we just don't even look at zero.
We also know that this code doesn't care about order. If digit 2 is in the number, it's always before digit 5. In other words, the code doesn't ever look at the number 52, only 25. Why? Because the smallest anagram number (numbers with the same digits in a different order) will always start with the smallest digit, then the second smallest, etc.
So, putting this all together:
void main(){
// Read in the target sum S
int S;
cin >> S;
// Set ans to be a value that's higher than anything possible
// Because the largest number with unique digits is 987654321.
int ans = 1e9;
// Go through each combination of digits, from 1 to 9.
for (int mask = 0; mask < 1 << 9; mask++) {
int sum = 0;
string num;
for (int i = 0; i < 9; i++)
// If this combination includes the digit i+1,
// Then add it to the sum, and append to the string representation.
if (mask >> i & 1) {
sum += i + 1;
num += char('0' + (i + 1));
}
// If this combination does not yield the right sum, try the next combination.
if (sum != S)
continue;
// If this combination does yield the right sum,
// see if it's smaller than our previous smallest.
ans = min(ans, stoi(num));
}
// Print the smallest combination we found.
cout << ans << '\n';
}
I hope this helps!
The for loop is iterating over all 9-digit binary numbers and turning those binary numbers into a string of decimal digits such that if nth binary digit is on then a n+1 digit is appended to the decimal number.
Generating the numbers this way ensures that the digits are unique and that zero never appears.
But as #Welbog mentions in comments this solution to the problem is way more complicated than it needs to be. The following will be an order of magnitude faster, and I think is clearer:
int smallest_number_with_unique_digits_summing_to_s(int s) {
int tens = 1;
int answer = 0;
for (int n = 9; n > 0 && s > 0; --n) {
if (s >= n) {
answer += n * tens;
tens *= 10;
s -= n;
}
}
return answer;
}
Just a quick way to on how code works.
First you need to know sum of which digits equal to S. Since each digit is unique, you can assign a bit to them in a binary number like this:
Bit number Digit
0 1
1 2
2 3
...
8 9
So you can check all numbers that are less than 1 << 9 (numbers with 9 bits corresponding 1 to 9) and check if sum of bits if equal to your sum based on their value. So for example if we assume S=17:
384 -> 1 1000 0000 -> bit 8 = digit 9 and bit 7 = digit 8 -> sum of digits = 8+9=17
Now that you know sum if correct, you can just create number based on digits you found.
I'm trying to solve the following problem, which how to add two strings without converting them to integer. I have found a solution to the problem, but I don't understand it. Would someone explain it in plain english please ?
here is the code :
class Solution {
public:
string addStrings(string num1, string num2) {
int i=num1.size()-1,j=num2.size()-1,carry=0;
string res="";
while(i>=0||j>=0)
{
if(i>=0) carry+=num1[i--]-'0';
if(j>=0) carry+=num2[j--]-'0';
res=to_string(carry%10)+res;
carry/=10;
}
return carry?"1"+res:res;
}
};
Okay! Lemme explain to you. Numbers are from 0-9. So, maximum sum possible is <=18. So, we need to take a flag/count/carry dummy variable which will be 1 when our sum exceeds 10 (num1[i]-'0'+num2[i]-'0'>=10).
When we add two numbers we start from the end. Same here we will loop from end to start i.e. while(i>=0 or j>=0 or count). Count is in while statement 'coz what if i=0 &/| j=0 sum is more than 10 then we will need to add an extra one to the start of the string.
Add elements from both strings and decrement corresponding counter i--, j--. Add carry either 0 or 1. calculate new carry which will be passed on to the next sum calculation. Take modulo of sum as we want a single digit. Covert it into string and append to res.
My Code
class Solution {
public:
string addStrings(string num1, string num2) {
int n1 = num1.size(), i = n1 - 1;
int n2 = num2.size(), j = n2 - 1;
int carry = 0;
string res = "";
while(i>=0 || j>=0 || carry){
long sum = 0;
if(i >= 0){sum += (num1[i] - '0');i--;}
if(j >= 0){sum += (num2[j] - '0');j--;}
sum += carry;
carry = sum / 10;
sum = sum % 10;
res = to_string(sum) + res;
}
return res;
}
};
I would like to count the number of decimal digits after the radix point of a floating point number.
The problem obviously raise when the real number doesn't have a representation in the binary system, like 3.5689113.
I am wondering - if for example someone write this real in a source code - if it is possible to get the number 7 namely the number of digits after the radix point
the naive following code for example doesn't work :
int main()
{
double num = 3.5689113;
int count = 0;
num = abs(num);
num = num - int(num);
while ( abs(num) >
0.0000001 )
{
num = num * 10;
count = count + 1;
num = num - int(num);
}
std::cout << count; //48
std::cin.ignore();
}
When something like that doesn't work, you try to print the numbers.
I did so here, and I found you had some floating number precision issues.
I changed the int rounding to ceil rounding and it worked like a charm.
Try putting the ints back and you'll see :)
EDIT: a better strategy than using ceils (which can give the same rounding problems) is to just round the numbers to the nearest integer. You can do that with floor(myNumber+0.5).
Here's the modified code
int main()
{
double num = 3.56891132326923333;
// Limit to 7 digits
num = floor(num*10000000 + 0.5)/10000000;
int count = 0;
num = abs(num);
num = num - floor(num+0.5);
while ( abs(num) >
0.0000001 )
{
cout << num << endl;
num = num * 10;
count = count + 1;
num = num - floor(num+0.5);
}
std::cout << count; //48
std::cin.ignore();
return 0;
}
To prevent the errors introduced by floating point approximation, convert the number to an integer at the earliest possible opportunity and work with that.
double num = 3.5689113;
int count = 7; // a maximum of 7 places
num = abs(num);
int remainder = int(0.5 + 10000000 * (num - int(num)));
while ( remainder % 10 == 0 )
{
remainder = remainder / 10;
--count;
}
For a floating point type T you can get up to std::numeric_limits<T>::digits10 digits restored exactly. Thus, to determine the position of the last non-zero fractional digits you'd use this value as a precision and format the number. To avoid the output using exponent notation you need to set the formatting flags to std::ios_base::fixed and account for the number of non-fractional digits:
std::ostringstream out;
int non_fraction(std::abs(value) < std::numeric_limits<double>::epsilon()
? 1: (1 + std::log(std::abs(value)) / std::log(10)));
out << std::setprecision(std::numeric_limits<double>::digits10 - non_fraction)
<< std::fixed
<< value;
If there is a decimal point, you just need to count the number of digits up to the trailing sequence of zeros.
I would recommend converting to a string, then looping over it and counting how many chars occur after you hit the period. Below is a sample (may need some minor tinkering, been awhile since I've done this in C++);
bool passedRadix = false
int i = 0; // for counting decimals
std::ostringstream strs;
strs << dbl; // dbl is 3.415 or whatever you're counting
std::string str = strs.str();
for(char& c : str) {
if (passedRadix == true)
i++;
if (c == '.')
passedRadix = true;
}
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.
Could anyone please tell me how to check what number I've got from a * b? Which is I would like to know every part of this number so for example if the result from this expression would be 25 I would like to know that first digit is two and second digit is five.
perhaps a little overkill... but even works with doubles
#include <sstream>
#include <iostream>
int main()
{
double a = 5.2;
double b = 7;
double z = a*b;
std::stringstream s;
s << z;
for (int i = 0; i < s.str().length(); i++)
std::cout << i << ": " << s.str()[i] << std::endl;
return 0;
}
a mod 10 == last digit of a
a / 10 == a without its last digit
So, for 25:
25 % 10 == 5 => 5 is the last digit of 25
25 / 10 == 2
2 % 10 == 2 => 2 is the first digit of 25
You can use these in a while loop to get each digit.
while (num > 0)
{
digit = num % 10;
// digit is now the current digit, counting from the right towards the left.
num /= 10;
}
int val = res;
while( val > 0 )
{
std::cout << val % 10 << endl;
val /= 10;
}
You have to get the result of the integer division by the appropriate power of ten.
int exp = std::floor( std::log10( num ) );
int first_digit = num / int( std::pow( 10.0, exp ) );
This is an (inefficient) way to get the first digit directly. It would be better to iterate starting from the last.
char str[30];
sprintf(str,"%d",a*b);
int ndigits = strlen(str);
There you have all digits of your value in the string, and the number of digits in ndigits.
e.g. if a*b = 25 you get
ndigits==2
str[ndigits-1]=='5'
str[ndigits-2]=='2'
What do you want this for?
There's probably an underlying misunderstanding here. The result of the multiplication will most likely be 0x00000019. (Number of leading zeroes will differ). The second step, converting it to canonical decimal will yield "25".
It's important to realize that computers, unlike normal humans, don't do their math in decimal but in binary. Hence, if you want to check a property like "last decimal digit of a number", it's not directly available to them.
Just remember, that e.g. 2101 is basically just 2*10^3 + 1*10^2 + 0*10^1 + 1*10^0.