将整数拆分为其数字 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4207696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split an Integer into its digits c++
提问by nkuebelbeck
I'm trying to learn c++ on my own and I've hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and display them.
我正在尝试自己学习 C++,但遇到了一些障碍。问题是我需要取一个整数,将其拆分为数字并获得数字的总和并显示它们。
Example:
例子:
input number: 123456
digits in the integer: 1 2 3 4 5 6
sum: 21
输入数字:123456
整数中的数字:1 2 3 4 5 6
总和:21
I have it all done, but when I rip the integer, into digits I can't display it correctly. It displays in reverse order.
我已经完成了,但是当我将整数翻录成数字时,我无法正确显示它。它以相反的顺序显示。
So in the program below I enter 1234
and it spits out 4 3 2 1
. I know why, I just don't know how to fix it.
所以在下面的程序中,我输入1234
并吐出4 3 2 1
。我知道为什么,我只是不知道如何解决它。
Here is my code so far:
到目前为止,这是我的代码:
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>
int countDigitsInInteger(int n)
{
int count =0;
while(n>0)
{
count++;
n=n/10;
}
return count;
}
using namespace std;
int main(int argc, char *argv[])
{
int intLength =0;
int number;
int digit;
int sum = 0;
string s;
cout << "Please enter an integer ";
cin >>number;
cout << "Orginal Number = "<<number <<endl;
//make the number positive
if (number<0)
number = -number;
intLength = countDigitsInInteger(number);
//break apart the integer into digits
while(number>0)
{
digit = number % 10;
number = number / 10;
cout <<digit << " ";
sum = sum+digit;
}
cout <<endl <<"Sum of the digits is: "<<sum<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Here is my solution
这是我的解决方案
can't see :)
看不到:)
回答by riwalk
Your problem comes from the fact that you are reading the digits backwards, thus you need to print them out backwards. A stackwill help you tremendously.
您的问题来自您向后读取数字的事实,因此您需要向后打印它们。一个堆栈将极大地帮助你。
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stack>
int countDigitsInInteger(int n)
{
int count =0;
while(n>0)
{
count++;
n=n/10;
}
return count;
}
using namespace std;
int main(int argc, char *argv[])
{
int intLength =0;
int number;
int digit;
int sum = 0;
string s;
cout << "Please enter an integer ";
cin >>number;
cout << "Orginal Number = "<<number <<endl;
//make the number positive
if (number<0)
number = -number;
intLength = countDigitsInInteger(number);
//break apart the integer into digits
stack<int> digitstack;
while(number>0)
{
digit = number % 10;
number = number / 10;
digitstack.push(digit);
sum = sum+digit;
}
while(digitstack.size() > 0)
{
cout << digitstack.top() << " ";
digitstack.pop();
}
cout <<endl <<"Sum of the digits is: "<<sum<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Oh, and BTW, keep your indentation clean. Its important.
哦,顺便说一句,保持你的缩进干净。这一点很重要。
EDIT: In response to Steve Townsend, this method is not necessarily overkill, it is just different from yours. The code can be slimmed down so that it seems less like overkill:
编辑:为了回应史蒂夫汤森,这种方法不一定是矫枉过正,它只是与你的不同。可以精简代码,使其看起来不那么矫枉过正:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int getInput(string prompt)
{
int val;
cout << prompt;
cin >> val;
return val < 0 ? -val : val;
}
int main(int argc, char** argv)
{
int num = getInput("Enter a number: ");
cout << "Original Number: " << num << endl;
stack<int> digits;
int sum = 0;
while(num > 0)
{
digits.push(num % 10);
sum += digits.top();
num = num / 10;
}
while(digits.size() > 0)
{
cout << digits.top() << " ";
digits.pop();
}
cout << endl << "Sum of digits is " << sum << endl;
return 0;
}
回答by Steve Townsend
Stack and recursion is overkill for this problem. Just store each digit into a stringand then reverseit before output. You need to work out how to call reverse
with the string
members for this to work. for_eachcan be used to output each element of the string.
堆栈和递归对于这个问题来说太过分了。只需将每个数字存储到一个字符串中,然后在输出之前将其反转。您需要弄清楚如何reverse
与string
成员通话才能使其工作。 for_each可用于输出字符串的每个元素。
For extra credit (by virtue of conciseness and expressiveness), insert the number directly into an ostringstreamand use that as the basis for your reversible string
.
为了获得额外的荣誉(凭借简洁性和表现力),将数字直接插入ostringstream并将其用作可逆的基础string
。
My stringstream
version of this code is 5 lines long. Logic is:
我stringstream
的这段代码版本有 5 行。逻辑是:
- declare stringstream
- declare int with value
- output int to stringstream
- create string from stringstream
- output the result digit by digit using
for_each
.
- 声明字符串流
- 用值声明 int
- 输出 int 到 stringstream
- 从字符串流创建字符串
- 使用 逐位输出结果
for_each
。
You can sum the digits using accumulateon the string, provide you account for the fact that int('1') != 1
. That's an extra two lines, to sum the digits and output the result.
您可以使用累加在字符串上对数字求和,前提是您考虑到int('1') != 1
. 这是额外的两行,用于对数字求和并输出结果。
The point is not that doing this via stack or recursion is BAD, it's just that once you get more familiar with the STL there are typically more elegant ways to do a job than the obvious. Implementing this using stack, recursion and any other ways you can think of makes a simple homework into a great real-world learning experience.
关键不是通过堆栈或递归来做这件事是不好的,只是一旦你对 STL 更加熟悉,通常会有比显而易见的更优雅的方式来完成工作。使用堆栈、递归和您能想到的任何其他方式来实现这一点,可以将简单的作业变成一个很棒的现实世界的学习体验。
Here's the accumulate
code to sum the members of a string
consisting of decimal digits, for example:
这是对由十进制数字组成的accumulate
a 的成员求和的代码string
,例如:
#include <string>
#include <numeric>
std::string intString("654321");
int sum = accumulate(intString.begin(), intString.end(), 0) -
(intString.size() * int('0'));
EDIT: here's the full code, for comparative purposes:
编辑:这是完整的代码,用于比较目的:
ostringstream intStream;
int value(123456);
intStream << value;
string intString(intStream.str());
for_each(intString.begin(), intString.end(), [] (char c) { cout << c << endl; });
int sum = accumulate(intString.begin(), intString.end(), 0) -
(intString.size() * int('0'));
cout << "Sum is " << sum << endl;
回答by karlphillip
Let's not forget the stringstreamapproach, which I also find elegant.
我们不要忘记stringstream方法,我也觉得它很优雅。
#include <iostream>
#include <sstream>
int main()
{
int num = 123456789;
std::cout << "Number: " << num << std::endl;
std::stringstream tmp_stream;
tmp_stream << num;
std::cout << "As string: " << tmp_stream.str() << std::endl;
std::cout << "Total digits: " << tmp_stream.str().size() << std::endl;
int i;
for (i = 0; i < tmp_stream.str().size(); i++)
{
std::cout << "Digit [" << i << "] is: " << tmp_stream.str().at(i) << std::endl;
}
return 0;
}
Outputs:
输出:
Number: 123456789
As string: 123456789
Total digits: 9
Digit [0] is: 1
Digit [1] is: 2
Digit [2] is: 3
Digit [3] is: 4
Digit [4] is: 5
Digit [5] is: 6
Digit [6] is: 7
Digit [7] is: 8
Digit [8] is: 9
回答by Finer Recliner
digit = number % 10;
This operation will return the the right most number.
此操作将返回最正确的数字。
so when you try to your app with an input "1357", on the first run through the while loop, it will return 7. Next it will return 5, and so on.
因此,当您尝试使用输入“1357”访问您的应用程序时,在第一次运行 while 循环时,它将返回 7。接下来它将返回 5,依此类推。
If all you want is the sum of the individual digits, then the order you get them (and print them out) will not affect the final answer. If you still want them to printed in the correct order, you can store the digits in an array (or Vector or Stack, as others have mentioned), reverse the contents, and then loop through the structure, to print out its contents.
如果您想要的只是各个数字的总和,那么您获取它们(并打印出来)的顺序将不会影响最终答案。如果您仍然希望它们以正确的顺序打印,您可以将数字存储在数组(或向量或堆栈,正如其他人提到的)中,反转内容,然后循环遍历结构,打印出其内容。
回答by tpdi
Push the digits onto a stack.
将数字压入堆栈。
After you've gotten all the digits,
在你得到所有的数字后,
sum = 0 ;
while( stack not empty ) {
pop the stack to get a digit
sum += digit
display digit
}
display sum
You need a stack, you say? Use the STL's stack: std::stack<int>
你需要一个堆栈,你说?使用 STL 的堆栈:std::stack<int>
回答by BugShotGG
A simple solution:
一个简单的解决方案:
int n = 12345;
vector<int> digits;
while (n != 0) {
digits.insert(digits.begin(), n%10);
n /= 10;
}
for(auto & i : digits)
cout << i << " ";
output: 1 2 3 4 5
输出:1 2 3 4 5
回答by Nim
I will put an example up in good faith that you will not reproduce it, if this is a homework assignment, use it as a chance to learn...
我会真诚地举一个例子,你不会复制它,如果这是一个家庭作业,把它作为一个学习的机会......
// reference: www.cplusplus.com
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
// What does this do?
template <typename T>
struct gen
{
gen(T start) : _num(start) {}
// Do we need these? But why have I commented them out?
//gen(gen const& copy) : _num(copy._num) {}
//gen& operator=(gen const& copy) { _num = copy._num; }
//~gen() {}
// Why do we do this?
T operator()() { T digit = _num % 10; _num /= 10; return digit; }
T _num;
};
// How is this different to the above?
template <typename T>
bool check_non_zero (T i)
{
return i != 0;
}
// And this? what's going on here with the parameter v?
template <typename T, int _size>
T sum_of_digits(T value, std::vector<T>& v)
{
// Why would we do this?
if (value == 0)
{
v.push_back(0);
return 0;
}
// What is the purpose of this?
v.resize(_size);
// What is this called?
gen<T> gen_v(value);
// generate_n? What is this beast? what does v.begin() return? where did _size come from?
generate_n(v.begin(), _size, gen_v);
// reverse? what does this do?
reverse(v.begin(), v.end());
// erase? find_if? what do they do? what the heck is check_non_zero<T>?
v.erase(v.begin(), find_if(v.begin(), v.end(), check_non_zero<T>));
// what the heck is accumulate?
return accumulate(v.begin(), v.end(), 0);
}
int main()
{
// What does this do?
vector<int> v;
// What is this peculiar syntax? NOTE: 10 here is because the largest possible number of int has 10 digits
int sum = sum_of_digits<int, 10>(123, v);
cout << "digits: ";
// what does copy do? and what the heck is ostream_iterator?
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
cout << "sum: " << sum << endl;
// other things to consider, what happens if the number is negative?
return 0;
}
回答by deetu
I used this for input for 5 numbers
我用它来输入 5 个数字
int main () {
int main () {
using namespace std;
using namespace std;
int number
;`
int number
;`
cout << "Enter your digit: ";
cin >> number;
if (number == 0)
return 0;
int a = number % 10;
int second = (number / 10);
int b = second % 10;
int third = (second / 10);
int c = third % 10;
int fourth = (third / 10);
int d = fourth % 10;
int fifth = (fourth / 10);
int e = fifth % 10;
cout << e << " " << d << " " << c << " " << b << " " << a << endl;
return 0;
}
}
回答by fabrizioM
Being a sum does not really matter the order, but the logic you are using splits it from the least significant digit to the most significant ( and is the easiest way).
作为一个和并不重要,但您使用的逻辑将它从最低有效数字拆分为最高有效数字(并且是最简单的方法)。
回答by fabrizioM
Use std::stack to store separate digits, then print out the contents of stack.
使用 std::stack 存储单独的数字,然后打印出堆栈的内容。
here is a nice article: http://en.wikipedia.org/wiki/Stack_(data_structure)
这是一篇不错的文章:http: //en.wikipedia.org/wiki/Stack_(data_structure)
here is how to use stacks in C++: http://www.sgi.com/tech/stl/stack.html
以下是如何在 C++ 中使用堆栈:http: //www.sgi.com/tech/stl/stack.html