从整数中删除数字

时间:2018-01-10 19:09:46

标签: java

这是我遇到的家庭作业问题:

  

输入一个大于或等于0的整数。将它乘以5,将6加到乘积上,乘以4,加9并乘以5.然后,删除最后一个数的最后两位数并减去1输出答案。调用Java类Computations。

我通过将输入转换为字符串,将其切片并将其转换回整数来解决它。这是我的代码:

import java.util.Scanner;

public class Computations {

    private static Scanner input = new Scanner(System.in);


    public static void main(String[] args) {

        boolean legal = false;
        int integer = -1;

        System.out.println("Enter an integer: ");
        do {
            if (input.hasNextInt() && input.nextInt()>=0) {
                legal = true;
                integer = input.nextInt();
            } else {
                System.out.println("Illegal input!");
            }
        } while (!legal);
        System.out.println(((((integer * 5) + 6) * 4 + 9) * 5)/100-1);
    }
}

在这里,我将所有内容放在一起,这样做是否会影响可读性并使其难以理解?

6 个答案:

答案 0 :(得分:7)

最简单的解决方案实际上是只输出输入 - 只要输入介于0和21,474,834之间。

给定的等式给出与输入相同的值。前几个操作给了我们:

5 * (4 * (5x + 6) + 9)
=   20 * (5x + 6) + 45
=       100x + 165

"删除最后两位"相当于除以100并截断小数部分(我们可以使用floor作为输入是非负的),这给出了:

floor((100x + 165) / 100) = floor(x + 1.65) = x + 1

减去1然后只给x输入。

如果计算溢出,则不一定会给出相同的输入。 Java中的int是带符号的32位整数,因此我们可以存储的最大值是2 31 -1 = 2,147,483,647。如果等式中最大的中间值超过这个,我们就不会得到正确的答案:

100x + 165 <= 2147483647

给出最大x,此方法将给出与执行每个操作的方法相同的值,如21,474,834。

所有这些说,你的(更新的)代码是一个很好的解决方案,并且完全可读。您应该考虑引入错误检查(您的引用说输入必须是>=0,这值得强制执行。)

添加注释,解释&#34;整数除以100用于修剪最后两位&#34;也许这是一个好主意,因为后来读取代码的开发人员可能会认为你犯了一个错误(没有意识到它会被截断)。每当您依赖异常行为时,记录

答案 1 :(得分:4)

您可以在这里使用

int i = (integer/100)-1;

答案 2 :(得分:3)

  

然后,删除最后一个数字的最后两位数并减去1。

为什么不除以100然后减去1

iTotal = (((iTotal * 5) + 6) * 4 + 9) * 5;
iTotal = (iTotal / 100) - 1; 

另外,将变量名称保留为integer并不是一个好习惯。

答案 3 :(得分:1)

您可以在代码中尝试此行:

int digit = (integer/100)-1;

答案 4 :(得分:0)

我相信你可以将数字除以100,然后将其截断。 类似的东西:

removing_last_2 = (int) integer/100;

或者,如果您可以保证该号码始终为正数:

removing_last_2 = Math.floor(integer/100);

答案 5 :(得分:0)

由于这是一个家庭作业问题,我会尽力指出你正确的方向。

您可以使用算术解决此问题,而无需将其转换为字符串。我建议您使用Remainder Operatorimport bs4 as bs import requests import re def is_number(s): try: int(s) return True except ValueError: return False def main(): url = 'https://www.nga.org/cms/FormerGovBios?inOffice=Any&state=Any&party=&lastName=&firstName=&nbrterms=Any&biography=&sex=Any&religion=&race=Any&college=&higherOfficesServed=&militaryService=&warsServed=&honors=&birthState=Any&submit=Search' sauce = requests.get(url).text soup = bs.BeautifulSoup(sauce, "html.parser") finished = False csv_data = open('Govs.csv', 'a') csv_data.write('Name,Address,OfficeDates,Success,Address,Phone,Fax,Born,BirthState,Party,Schooling,Email') try: while not finished: #dl links to each gov table = soup.find('table', 'table table-striped table-striped') links = table.findAll('a') for link in links: info_array = [] gov = {} name = link.string gov_sauce = requests.get(r'https://nga.org'+link.get('href')).text gov_soup = bs.BeautifulSoup(gov_sauce, "html.parser") #print(gov_soup) office_and_stuff_info = gov_soup.findAll('address') for address in office_and_stuff_info: infos = address.findAll('p') for info in infos: tex = re.sub('[^a-zA-Z\d:]','',info.text) tex = re.sub('\\s+',' ',info.text) tex = tex.strip() if tex: info_array.append(tex) info_array = list(set(info_array)) gov['Name'] = name secondarry_address = '' gov['Address'] = '' for line in info_array: if 'OfficeDates:' in line: gov['OfficeDates'] = line.replace('OfficeDates:','').replace('-','') elif 'Succ' or 'Fail' in line: gov['Success'] = line elif 'Address' in line: gov['Address'] = line.replace('Address:','') elif 'Phone:' or 'Phone ' in line: gov['Phone'] = line.replace('Phone ','').replace('Phone: ','') elif 'Fax:' in line: gov['Fax'] = line.replace('Fax:','') elif 'Born:' in line: gov['Born'] = line.replace('Born:','') elif 'Birth State:' in line: gov['BirthState'] = line.replace('BirthState:','') elif 'Party:' in line: gov['Party'] = line.replace('Party:','') elif 'School(s)' in line: gov['Schooling'] = line.replace('School(s):','').replace('School(s) ') elif 'Email:' in line: gov['Email'] = line.replace('Email:','') else: secondarry_address = line gov['Address'] = gov['Address'] + secondarry_address data_line = gov['Name'] +','+gov['Address'] +','+gov['OfficeDates'] +','+gov['Success'] +','+gov['Address'] +','+ gov['Phone'] +','+ gov['Fax'] +','+gov['Born'] +','+gov['BirthState'] +','+gov['Party'] +','+gov['Schooling'] +','+gov['Email'] csv_data.write(data_line) next_page_link = soup.find('ul','pagination center-blockdefault').find('a',{'aria-label':'Next'}) if next_page_link.parent.get('class') == 'disabled': finished = True else: url = r'https://nga.org'+next_page_link.get('href') sauce = requests.get(url).text soup = bs.BeautifulSoup(sauce,'html.parser') except: print('Code failed.') finally: csv_data.close() if __name__ == '__main__': main()

示例:

%

返回:

124 % 4

可是:

0

返回:

124 % 3

取余数并将其从总数中移除以获得所需的输出。

至于优雅,没有通用的标准。我们的想法是让您的代码尽可能简单易读。将逻辑提取到私有方法是一个良好的开端。

至于Haskell,我不知道。你将不得不做一些网络搜索。