我有一组数字是1-9。我有一组可变的数字(例如1-3、1-4或1-7等等)。我需要把第二组数字(变量)集中到第一组。如果第二组数字是偶数,那么将第二组移动到1。
示例:
123456789 000123000
在上面的例子中,4与1相关,5与2相关,6与3相关。
或
123456789 001234000
或
123456789 012345670
我很难解决这个问题,这样我就可以把第二行文字从第一行中划出来。"0“并不重要,并添加到示例中以显示空间差异。我认为这是基本的数学,但我遗漏了一些东西。谢谢你的帮忙!
编辑#1:
package com.company;
public class Main {
private static final int maxNumberOfItems = 9;
public static void main(String[] args) {
int numberOfItems = 6; // Any number between 1 and 9.
int difference = maxNumberOfItems - numberOfItems;
int dividedDifference;
boolean isEven = (numberOfItems % 2) == 0;
if (isEven) {
dividedDifference = (difference - 1) / 2;
} else {
dividedDifference = difference / 2;
}
printAnswer(numberOfItems, dividedDifference, isEven);
}
private static void printAnswer(int numberOfItems, int dividedDifference, boolean isEven) {
//TODO: Print answer here to console.
// Desired output:
// 123456789 (represents maxNumberOfItems)
// --1234--- (represents numberOfItems)
// Pseudo logic.
// Figure out if the var numberOfItems is odd or even.
// If its odd, subtract the numberOfItems from the maxNumberOfItems.
// Take that number and divide by two. That gives the amount of spaces to skip on each side.
// If the number is even, subtract one and divide by two. Get the number of spaces on each side
// and add one back to the right side.
}
}编辑2:
@Mbo要求我详细解释“真正的问题”。就这么办了。在一个3D世界中,我有一组基座,它将根据要显示的项目数量在四分之一圈内产生。基座位置在固定的XYZ坐标处。这些坐标永远不会改变。这些地点如下图所示。最多只能有9个基座。我们想要显示的基座是基于我们想要显示的“项”(我们的变化变量)的数量。理想情况下,我们总是想在中间展示给他们看。如果数字是偶数,那么我们想要显示中间的基座,但接近1比9。这个数字可以显示在问题的顶部,在块引号中。
123456789 001234000
示例图像:代表四分之一圈和基座的位置。
最好有一个地图或HashMap保存关键项目编号和价值基座的位置。只要显示一个基座,就会始终使用位置5。
因此,如果给出一张地图,它可能看起来像这样。
示例1:
4项。[9]可能要展示的基座。
项目1(键)到基座3的位置(值)。 第2项(键)至基座4位置(值)。 第3项(键)至基座5位置(值)。 第4项(键)至基座6的位置(值)。
请注意,上面的示例4并没有均匀地划分为9,因此中心位置被偏移并位于接近1的位置。
示例2:
3项。[9]可能要展示的基座。
第1项(键)至基座4位置(值)。 第2项(键)至基座5位置(值)。 第3项(键)至基座6位置(值)。
在本例中,3被很好地划分为9,因此它可以完美地居中。
这才是真正的问题。
发布于 2017-07-12 15:44:44
实现算法的方法之一是:
public class Main {
private static final int maxNumberOfItems = 9;
public static void main(String[] args) {
int numberOfItems = 1531; // Any number between 1 and 9.
int strLength = Integer.toString(numberOfItems).length(); // the length of the string presentation
printAnswer(numberOfItems, strLength, maxNumberOfItems);
}
private static void printAnswer(int number, int start, int max) {
String str = Integer.toString(number);
for (int i = start; i < max; i++) {
if (i % 2 == 0) { // in this conditions we define from
str += "0"; // which side we need to append "0"
} else {
str = "0" + str;
}
}
System.out.println(str);
}
}此实现的主要思想是在字符串中添加从两侧到字符串的现有数字解释所需的"0“数量。
输出:
001531000https://stackoverflow.com/questions/45046897
复制相似问题