我是C#的新手,我对问题感到非常难过。
我正在尝试在控制台应用中添加相同长度的用户输入的每个数字(例如:数字1 = 123&2;数字2 = 456)。所以我想查看是否1 + 4 = 2 + 5 = 3 + 6,然后说出它是真还是假。
我的问题是,我不知道如何挑出已输入的每个数字。我觉得我绝对不会想到这一点,但任何帮助都会受到赞赏。
答案 0 :(得分:4)
让我们用一般情况和最准确的方式解决问题。首先,我们应该回答两个问题:
-
或返回false
?52
和3
?我们应该将3
填入03
(然后返回true
)或返回false
吗?实施
public static bool Solution(int left, right) {
// Comment this out (drop) if you accept negative numbers
if (left < 0 || right < 0)
return false;
// Trim('-') - trimming '-' if we have negative numbers
string A = left.ToString(CultureInfo.InvariantCulture).Trim('-');
string B = right.ToString(CultureInfo.InvariantCulture).Trim('-');
// Comment this out (drop) if you want to pad numbers with different lengths
if (A.Length != B.Length)
return false;
// Padding with zeroes if required
if (A.Length > B.Length)
B = B.PadLeft(A.Length, '0');
else if (B.Length > A.Length)
A = A.PadLeft(B.Length, '0');
// Finally, we can check
for (int i = 1; i < A.Length; ++i)
if (A[i] + B[i] != A[0] + B[0])
return false; // Do we have a counter example?
return true;
}
答案 1 :(得分:3)
您可以使用LINQ:
//Might be your view code behind or
//ViewModel if you are using MVVM
public class ViewCodeBehind
{
public List<ComboBind> ComboItems { get; set; }
public void Initialize()
{
//start bacground task for data loading
var comboQuery = "select *from data";
Task.Run(() => LoadItems(comboQuery));
}
public void LoadItems(string query)
{
List<ComboBind> values = new List<ComboBind>();
try
{
using (var oleDbCommand = new OleDbCommand())
{
oleDbCommand.CommandText = query;
oleDbCommand.Connection = Connection.con;
var sql = query;
var oleDbDataReader = oleDbCommand.ExecuteReader();
while (oleDbDataReader.Read())
{
ComboBind b = new ComboBind();
b.id = oleDbDataReader[0].ToString().ToInt();
b.name = oleDbDataReader[1].ToString();
values.Add(b);
}
}
//use dispatcher to pass data back to UI thread
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() =>
{
ComboItems = values;
}));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
string number1 = "123";
string number2 = "456";
bool equalSums = number1
.Zip(number2, (c1, c2) => Convert.ToInt32(c1) + Convert.ToInt32(c2))
.Distinct()
.Count() == 1;
通过索引链接两个序列,因此第一个字符串的char1与其他字符串的char1链接,依此类推。 Enumerable.Zip
将字符转换为Convert.ToInt32
并构建两位数的总和。然后int
删除重复项并Distinct
检查是否只剩下一个数字,这意味着所有数字相等。
答案 2 :(得分:-1)
这是显示正则表达式的一个很大的问题,假设你的数字存储在属性中,
string num1 = Console.ReadLine();
string num2 = Console.ReadLine();
int[] numbers1 = (from Match m in Regex.Matches(num1 , @"\d") select
int.Parse(m.Value)).ToArray();
int[] numbers2 = (from Match m in Regex.Matches(num2 , @"\d") select int.Parse(m.Value)).ToArray();
然后你有两个可以测试的数字数组e / g
if (numbers1[1] + numbers2[1] == numbers1[2] + numbers2[2])
{
Console.WriteLine("aye its true");
}
else {
//do something else
}
我希望能回答你的问题
P.S。我使用Regex 101来测试我的正则表达式,这是一个很好的工具