gpt4 book ai didi

c# - 如何手动编程 Int.Parse()

转载 作者:行者123 更新时间:2023-12-02 06:28:46 25 4
gpt4 key购买 nike

我们有这个编码练习来手动实现 .Net 的 Int.Parse() 方法

我不明白他们的“正确”解决方案是如何工作的。但我记得它包括将字符除以十分之一、百分之一......

我找到了一个用Java函数完成的解决方案。有人可以向我解释一下如何将它乘以十来将字符串解析为 int 吗?

public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}

最佳答案

实际上这不是你完成家庭作业的地方:-)

但是,我记得,分析我的第一个程序是为了理解“一个人如何做这样的事情”。后来我总是习惯把外国代码重构成我能理解的更小的片段。

因此,对于上面的代码片段,这可能是:

public static int myStringToInteger(String str) {
int answer = 0;
int factor = 1;

// Iterate over all characters (from right to left)
for (int i = str.length() - 1; i >= 0; i--) {

// Determine the value of the current character
// (I guess this is the trick you were missing
// We extract a single character, subtract the
// ASCII value the character '0', getting the "distance"
// from zero. So we converted a single character into
// its integer value)
char currentCharacter = str.charAt( i );
int value = currentCharacter - '0';

// Add the value of the character at the right place
answer += value * factor;

// Step one place further
factor *= 10;
}

return answer;
}

关于c# - 如何手动编程 Int.Parse(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20262395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com