试题 算法训练 连续正整数的和 java 题解 118

问题描述

  78这个数可以表示为连续正整数的和,1+2+3,18+19+20+21,25+26+27。
  输入一个正整数 n(<=10000)
  输出 m 行(n有m种表示法),每行是两个正整数a,b,表示a+(a+1)+...+b=n。
  对于多种表示法,a小的方案先输出。

样例输入

78

样例输出

1 12
18 21
25 27

解题思路:

模拟双指针移动,通过将前后指针间元素之和判断是否是待求答案或需要调整指针。另外还需要对

边界值进行调试。

java代码:

import java.io.*;

public class Main {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		StringBuilder bu = new StringBuilder();
		for(int i = 1; i <= n / 2 + 1;) {
			int sum = i;
			int count = 0;
			for(int j = i + 1;j <= n/2 + 1;j++) {
				sum += j;
				count++;
				if(sum == n) {
					bu.append(i + " " + j + "\n");
					i = j - count + 1;
					break;
				}
				if(sum > n) {
					i = j  - count + 1;
					break;
				}
			}
			if(i >= n / 2  + 1)break;
		}
		System.out.print(bu.toString().trim());
	}
}

提交截图:

猜你喜欢

转载自blog.csdn.net/weixin_48898946/article/details/121060877