拆解数字

论坛上看到的一个题目:
http://www.iteye.com/topic/963980

将任一个数字进行拆解,例如:

3 = 2+1 = 1+1+1 所以3有三種拆法
4 = 3 + 1 = 2 + 2 = 2 + 1 + 1 = 1 + 1 + 1 + 1 共五種
5 = 4 + 1 = 3 + 2 = 3 + 1 + 1 = 2 + 2 + 1 = 2 + 1 + 1 + 1 = 1 + 1 +1 +1 +1 共七种


随便给一个数字,对其进行拆解,并打印可拆解情况和拆解结果数。

public class SplitNum {
public static void main(String[] args) {
System.out.println("一共有" + splitNumber(10) + "种分法");
}

public static int splitNumber(int a) {
return splitNumberWithMax(a, a, 0, a+" = ");
}

private static int splitNumberWithMax(int max, int tag, int c, String s) {
if (tag == 1 || tag == 0) {
System.out.println(tag == 1 ? (s + tag ) : s.substring(0,s.length()-2));
c++;
} else {
for (int i = (max >= tag ? tag : max); i > 0; i--) {
c = splitNumberWithMax(i, tag - i, c, s + i + " + ");
}
}
return c;
}
}



利用循环,不用递归,不用怎么担心内存的问题。
import java.util.Stack;

public class SplitNum2 {
public static void main(String[] args) {
System.out.println(splitNum(200));
}

public static int splitNum(int tag){
int a,b;
int c = 0;
Stack<Integer> s = new Stack<Integer>();
s.push(tag);
while(true){
c++;
System.out.print(c+":");
print(s);
while (!s.isEmpty() && s.peek() == 1) {
s.pop();
}
if (s.isEmpty())break;
a = s.pop();
s.push(--a);
do {
b = tag - sum(s);
if (b==0)break;
s.push(a<b?a:b);
} while (true);
}
return c;
}
private static int sum(Stack<Integer> s){
int sum = 0;
for (int i:s) {
sum += i;
}
return sum;
}

private static void print(Stack<Integer> s){
for (int i:s) {
System.out.print(i+"+");
}
System.out.println();
}

}
C++中,如果你想将n位数字正序拆解并输出,你可以通过循环和字符串连接的方式来实现。这里有一个简单的示例,假设你想将一个整数分解成每一位数字,并按顺序输出: ```cpp #include <iostream> #include <string> std::string decimalToBase(int num, int base) { std::string result; while (num > 0) { result = std::to_string(num % base) + result; // 余数放在前面 num /= base; } return result; } int main() { int nbit_number; // 输入的n位数字 std::cout << "请输入一个" << 8 << "-位数字: "; std::cin >> nbit_number; // 我们通常处理的是8位二进制数,所以转换为十进制表示 int decimal_num = nbit_number; if (decimal_num < 0 || decimal_num >= pow(2, 8)) { std::cerr << "输入无效,应为0到255之间的8位数字.\n"; return 1; } std::string binary_str = decimalToBase(decimal_num, 2); // 转换为二进制 std::cout << "二进制表示: " << binary_str << "\n"; // 输出二进制形式 for (char digit : binary_str) { // 按字符遍历输出 std::cout << digit; } std::cout << "\n每位数字逐次输出: \n"; // 拆解每个数字 for (size_t i = 0; i < binary_str.size(); ++i) { std::cout << binary_str[i] << " (" << i+1 << "位)"; if (i != binary_str.size() - 1) { std::cout << ", "; } } std::cout << "\n"; return 0; } ``` 这个程序首先会将输入的八位数字转换为二进制,然后逐位打印出来。如果输入不是有效的8位二进制数,它还会给出错误提示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值