二十四点--ccf(100分)

本文介绍了一种基于逆波兰表达式的算法实现,通过使用两个栈(运算数栈和运算符栈)来解析并计算逆波兰表达式。该算法能够处理加、减、乘、除等基本运算,并通过具体代码示例详细展示了算法的工作流程。
import java.util.LinkedList;
import java.util.Scanner;

/**
 * @author 
 */
public class ReversePolish {
    /**
      存储运算数的栈
    **
    /
    private LinkedList<Integer> operandStack  = new LinkedList<>();
    /**
    存储运算符的栈
    **/
    private LinkedList<Character> operatorStack  = new LinkedList<>();
    private static final char END = '#';
    private void reversePolish(){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        String compression;
        operatorStack.push(END);
        scanner.nextLine();
        for (int i = 0; i < n; i++) {
            int sum;
            compression = scanner.nextLine();
            for (int j = 0; j < compression.length(); j++) {
                switch (compression.charAt(j)){
                    case '+':if(operatorStack.getFirst() == END){
                        operatorStack.push('+');
                    }else{
                        sum = calculate(operatorStack.pop());
                        operatorStack.push('+');
                        operandStack.push(sum);
                    }break;
                    case '-':if(operatorStack.getFirst() == END){
                        operatorStack.push('-');
                    }else{
                        sum = calculate(operatorStack.pop());
                        operatorStack.push('-');
                        operandStack.push(sum);

                    }break;
                    case 'x':if(operatorStack.getFirst() == END || operatorStack.getFirst() == '+' || operatorStack.getFirst() == '-'){
                        operatorStack.push('x');
                    }else{
                        sum = calculate(operatorStack.pop());
                        operatorStack.push('x');
                        operandStack.push(sum);
                    }break;
                    case '/':if(operatorStack.getFirst() == END || operatorStack.getFirst() == '+' || operatorStack.getFirst() == '-'){
                        operatorStack.push('/');
                    }else{
                        sum = calculate(operatorStack.pop());
                        operatorStack.push('/');
                        operandStack.push(sum);
                    }break;
                    default:operandStack.push(Integer.parseInt(String.valueOf(compression.charAt(j))));
                }
            }
            while (operatorStack.getFirst() != END){
                sum = calculate(operatorStack.pop());
                operandStack.push(sum);
            }
            if(operandStack.pop() == 24){
                System.out.println("Yes");
            }else {
                System.out.println("No");
            }
        }
    }
    private int calculate(char operator){
        int op1 = operandStack.pop();
        int op2 = operandStack.pop();
        switch (operator){
            case '+':return op2 + op1;
            case '-':return op2 - op1;
            case 'x':return op2 * op1;
            // 除法
            default :return op2 / op1;
        }
    }

    public static void main(String[] args) {
        new ReversePolish().reversePolish();
    }
}

思路:其实就是一个正常算术表达式转换为逆波兰式的过程。需要一个运算数栈和一个运算符栈。对逆波兰式不熟悉的可以先看一下逆波兰式。

------------------------------------- Translated Report (Full Report Below) ------------------------------------- Process: SecureCRT [16150] Path: /Applications/SecureCRT.app/Contents/MacOS/SecureCRT Identifier: com.vandyke.SecureCRT Version: 8.5.1 (123345) Code Type: X86-64 (Translated) Parent Process: launchd [1] User ID: 501 Date/Time: 2025-08-24 13:35:52.8698 +0800 OS Version: macOS 15.6.1 (24G90) Report Version: 12 Anonymous UUID: 1C7673FA-21C1-09A0-ED0F-6AF4362E123E Sleep/Wake UUID: CD3C1889-8D6D-4C16-8760-173677E8CC3D Time Awake Since Boot: 11000 seconds Time Since Wake: 1133 seconds System Integrity Protection: disabled Notes: RIP register does not match crashing frame (0x0 vs 0x10621FAE0) Dyld Error Message: 1 Crashed Thread: 0 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: Namespace DYLD, Code 1 Library missing Library not loaded: /System/Library/Frameworks/Python.framework/Versions/2.7/Python Referenced from: <DB1CCF56-913E-336B-A18E-F5CE03220D7D> /Applications/SecureCRT.app/Contents/MacOS/SecureCRT Reason: tried: '/System/Library/Frameworks/Python.framework/Versions/2.7/Python' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/System/Library/Frameworks/Python.framework/Versions/2.7/Python' (no such file), '/System/Library/Frameworks/Python.framework/Versions/2.7/Python' (no such file, not in dyld cache), '/Library/Frameworks/Python.framework/Versions/2.7/Python' (no such file) (terminated at launch; ignore backtrace) Error Formulating Crash Report: RIP register does not match crashing frame (0x0 vs 0x10621FAE0) Thread 0 crashed with X86 Thread State (64-bit): rax: 0x0000000000000006 rbx: 0x0000000000000089 rcx: 0x0000000000000001 rdx: 0x000000030e2bbe40 rdi: 0x000000200e2bba20 rsi: 0xc40d5720273b004a rbp: 0x0000000000000000 rsp: 0x000000030e2bba40 r8: 0x000000030e2bba40 r9: 0x0000000000000000 r10: 0x0000000000000089 r11: 0x000000030e2bba40 r12: 0x0000000000000000 r13: 0x000000030e2bbe40 r14: 0x0000000000000006 r15: 0x0000000000000089 rip: <unavailable> rfl: 0x0000000000000283 tmp0: 0xffffffffffffffff tmp1: 0x000000010621fab4 tmp2: 0x000000020583d9f7 Binary Images: 0x2057b9000 - 0x205853fff dyld (*) <c6e52c5e-d1d2-354c-a4ec-069f8d5baafe> /usr/lib/dyld 0x7ff7ffd04000 - 0x7ff7ffd33fff runtime (*) <f49bd639-923b-3201-924b-695964df0712> /usr/libexec/rosetta/runtime 0x10e21f000 - 0x10e286fff libRosettaRuntime (*) <7742e99c-2006-3006-bc1e-1869448c6224> /Library/Apple/*/libRosettaRuntime 0x1049e9000 - 0x1053b9fff com.vandyke.SecureCRT (8.5.1) <db1ccf56-913e-336b-a18e-f5ce03220d7d> /Applications/SecureCRT.app/Contents/MacOS/SecureCRT 0x10e823000 - 0x10e86dfff libssl.1.0.0.dylib (*) <54c92cf6-401f-3a2f-b536-ec3d869e821d> /Applications/SecureCRT.app/Contents/Frameworks/libssl.1.0.0.dylib 0x10eb06000 - 0x10ec90fff libcrypto.1.0.0.dylib (*) <a23f708b-821b-3137-b2b6-5ec77b2d2dc4> /Applications/SecureCRT.app/Contents/Frameworks/libcrypto.1.0.0.dylib 0x0 - 0xffffffffffffffff ??? (*) <00000000-0000-0000-0000-000000000000> ??? External Modification Summary: Calls made by other processes targeting this process: task_for_pid: 0 thread_create: 0 thread_set_state: 0 Calls made by this process: task_for_pid: 0 thread_create: 0 thread_set_state: 0 Calls made by all processes on this machine: task_for_pid: 0 thread_create: 0 thread_set_state: 0 VM Region Summary: ReadOnly portion of Libraries: Total=14.1M resident=0K(0%) swapped_out_or_unallocated=14.1M(100%) Writable regions: Total=167.6M written=369K(0%) resident=369K(0%) swapped_out=0K(0%) unallocated=167.3M(100%) VIRTUAL REGION REGION TYPE SIZE COUNT (non-coalesced) =========== ======= ======= Rosetta Arena 4096K 2 Rosetta Generic 1160K 287 Rosetta IndirectBranch 32K 1 Rosetta JIT 128.0M 1 Rosetta Return Stack 20K 2 Rosetta Thread Context 20K 2 Stack 8176K 1 Stack Guard 56.0M 1 VM_ALLOCATE 4K 1 VM_ALLOCATE (reserved) 80K 3 reserved VM address space (unallocated) __DATA 2112K 11 __DATA_CONST 28K 1 __DATA_DIRTY 8K 2 __LINKEDIT 1288K 8 __TEXT 12.9M 6 __TPRO_CONST 4K 1 mapped file 15.1M 10 page table in kernel 369K 1 =========== ======= ======= TOTAL 228.9M 341 TOTAL, minus reserved VM space 228.8M 341 ----------- Full Report ----------- {"app_name":"SecureCRT","timestamp":"2025-08-24 13:35:53.00 +0800","app_version":"8.5.1","slice_uuid":"db1ccf56-913e-336b-a18e-f5ce03220d7d","build_version":"123345","platform":1,"bundleID":"com.vandyke.SecureCRT","share_with_app_devs":0,"is_first_party":0,"bug_type":"309","os_version":"macOS 15.6.1 (24G90)","roots_installed":0,"name":"SecureCRT","incident_id":"7BAD7F66-6395-4DB8-8EF8-3D405979C45F"} { "uptime" : 11000, "procRole" : "Default", "version" : 2, "userID" : 501, "deployVersion" : 210, "modelCode" : "Mac16,7", "coalitionID" : 7826, "osVersion" : { "train" : "macOS 15.6.1", "build" : "24G90", "releaseType" : "User" }, "captureTime" : "2025-08-24 13:35:52.8698 +0800", "codeSigningMonitor" : 2, "incident" : "7BAD7F66-6395-4DB8-8EF8-3D405979C45F", "pid" : 16150, "translated" : true, "cpuType" : "X86-64", "roots_installed" : 0, "bug_type" : "309", "procLaunch" : "2025-08-24 13:35:52.8025 +0800", "procStartAbsTime" : 281064369410, "procExitAbsTime" : 281065978749, "procName" : "SecureCRT", "procPath" : "\/Applications\/SecureCRT.app\/Contents\/MacOS\/SecureCRT", "bundleInfo" : {"CFBundleShortVersionString":"8.5.1","CFBundleVersion":"123345","CFBundleIdentifier":"com.vandyke.SecureCRT"}, "storeInfo" : {"deviceIdentifierForVendor":"415873C9-07F0-5291-8061-928014B61B58","thirdParty":true}, "parentProc" : "launchd", "parentPid" : 1, "coalitionName" : "com.vandyke.SecureCRT", "crashReporterKey" : "1C7673FA-21C1-09A0-ED0F-6AF4362E123E", "appleIntelligenceStatus" : {"reasons":["countryLocationIneligible","countryBillingIneligible","regionIneligible"],"state":"unavailable"}, "codeSigningID" : "com.vandyke.SecureCRT", "codeSigningTeamID" : "9M229JAFBZ", "codeSigningFlags" : 570425345, "codeSigningValidationCategory" : 6, "codeSigningTrustLevel" : 4294967295, "codeSigningAuxiliaryInfo" : 0, "bootSessionUUID" : "A817A699-2993-4012-BE2E-C11C02E0C228", "wakeTime" : 1133, "fatalDyldError" : 1, "sleepWakeUUID" : "CD3C1889-8D6D-4C16-8760-173677E8CC3D", "sip" : "disabled", "exception" : {"codes":"0x0000000000000000, 0x0000000000000000","rawCodes":[0,0],"type":"EXC_CRASH","signal":"SIGABRT"}, "termination" : {"code":1,"flags":518,"namespace":"DYLD","indicator":"Library missing","details":["(terminated at launch; ignore backtrace)"],"reasons":["Library not loaded: \/System\/Library\/Frameworks\/Python.framework\/Versions\/2.7\/Python","Referenced from: <DB1CCF56-913E-336B-A18E-F5CE03220D7D> \/Applications\/SecureCRT.app\/Contents\/MacOS\/SecureCRT","Reason: tried: '\/System\/Library\/Frameworks\/Python.framework\/Versions\/2.7\/Python' (no such file), '\/System\/Volumes\/Preboot\/Cryptexes\/OS\/System\/Library\/Frameworks\/Python.framework\/Versions\/2.7\/Python' (no such file), '\/System\/Library\/Frameworks\/Python.framework\/Versions\/2.7\/Python' (no such file, not in dyld cache), '\/Library\/Frameworks\/Python.framework\/Versions\/2.7\/Python' (no such file)"]}, "extMods" : {"caller":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"system":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"targeted":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"warnings":0}, "faultingThread" : 0, "threads" : [{"triggered":true,"id":235783,"threadState":{"flavor":"x86_THREAD_STATE","rbp":{"value":0},"r12":{"value":0},"rosetta":{"tmp2":{"value":8682461687},"tmp1":{"value":4397857460},"tmp0":{"value":18446744073709551615}},"rbx":{"value":137},"r8":{"value":13122648640},"r15":{"value":137},"r10":{"value":137},"rdx":{"value":13122649664},"rdi":{"value":137676700192},"r9":{"value":0},"r13":{"value":13122649664},"rflags":{"value":643},"rax":{"value":6},"rsp":{"value":13122648640},"r11":{"value":13122648640},"rcx":{"value":1},"r14":{"value":6},"rsi":{"value":14127043401739862090}},"frames":[{"imageOffset":4397857504,"region":"Rosetta Runtime Routines","symbolLocation":10976,"imageIndex":6},{"imageOffset":4398572220,"region":"<translation info unavailable>","imageIndex":6},{"imageOffset":543223,"symbol":"abort_with_payload_wrapper_internal","symbolLocation":82,"imageIndex":0},{"imageOffset":543273,"symbol":"abort_with_payload","symbolLocation":9,"imageIndex":0},{"imageOffset":44229,"symbol":"dyld4::halt(char const*, dyld4::StructuredError const*)","symbolLocation":343,"imageIndex":0},{"imageOffset":30973,"symbol":"dyld4::prepare(dyld4::APIs&, mach_o::Header const*)","symbolLocation":4300,"imageIndex":0},{"imageOffset":26655,"symbol":"dyld4::start(dyld4::KernelArgs*, void*, void*)::$_0::operator()() const","symbolLocation":239,"imageIndex":0},{"imageOffset":25818,"symbol":"start","symbolLocation":2970,"imageIndex":0}]},{"id":235784,"name":"com.apple.rosetta.exceptionserver","threadState":{"flavor":"x86_THREAD_STATE","rbp":{"value":9908489551872},"r12":{"value":0},"rosetta":{"tmp2":{"value":0},"tmp1":{"value":0},"tmp0":{"value":0}},"rbx":{"value":0},"r8":{"value":2307},"r15":{"value":0},"r10":{"value":0},"rdx":{"value":0},"rdi":{"value":0},"r9":{"value":1},"r13":{"value":0},"rflags":{"value":515},"rax":{"value":268451845},"rsp":{"value":0},"r11":{"value":0},"rcx":{"value":17314086914},"r14":{"value":0},"rsi":{"value":2616}},"frames":[{"imageOffset":16612,"imageIndex":1}]}], "usedImages" : [ { "source" : "P", "arch" : "x86_64", "base" : 8681918464, "size" : 634880, "uuid" : "c6e52c5e-d1d2-354c-a4ec-069f8d5baafe", "path" : "\/usr\/lib\/dyld", "name" : "dyld" }, { "source" : "P", "arch" : "arm64", "base" : 140703125487616, "size" : 196608, "uuid" : "f49bd639-923b-3201-924b-695964df0712", "path" : "\/usr\/libexec\/rosetta\/runtime", "name" : "runtime" }, { "source" : "P", "arch" : "arm64", "base" : 4532072448, "size" : 425984, "uuid" : "7742e99c-2006-3006-bc1e-1869448c6224", "path" : "\/Library\/Apple\/*\/libRosettaRuntime", "name" : "libRosettaRuntime" }, { "source" : "P", "arch" : "x86_64", "base" : 4372467712, "CFBundleShortVersionString" : "8.5.1", "CFBundleIdentifier" : "com.vandyke.SecureCRT", "size" : 10293248, "uuid" : "db1ccf56-913e-336b-a18e-f5ce03220d7d", "path" : "\/Applications\/SecureCRT.app\/Contents\/MacOS\/SecureCRT", "name" : "SecureCRT", "CFBundleVersion" : "123345" }, { "source" : "P", "arch" : "x86_64", "base" : 4538380288, "size" : 307200, "uuid" : "54c92cf6-401f-3a2f-b536-ec3d869e821d", "path" : "\/Applications\/SecureCRT.app\/Contents\/Frameworks\/libssl.1.0.0.dylib", "name" : "libssl.1.0.0.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 4541407232, "size" : 1617920, "uuid" : "a23f708b-821b-3137-b2b6-5ec77b2d2dc4", "path" : "\/Applications\/SecureCRT.app\/Contents\/Frameworks\/libcrypto.1.0.0.dylib", "name" : "libcrypto.1.0.0.dylib" }, { "size" : 0, "source" : "A", "base" : 0, "uuid" : "00000000-0000-0000-0000-000000000000" } ], "sharedCache" : { "base" : 140703325241344, "size" : 25769803776, "uuid" : "ee391b1f-8609-3a52-b9f2-37e2fecd47b7" }, "vmSummary" : "ReadOnly portion of Libraries: Total=14.1M resident=0K(0%) swapped_out_or_unallocated=14.1M(100%)\nWritable regions: Total=167.6M written=369K(0%) resident=369K(0%) swapped_out=0K(0%) unallocated=167.3M(100%)\n\n VIRTUAL REGION \nREGION TYPE SIZE COUNT (non-coalesced) \n=========== ======= ======= \nRosetta Arena 4096K 2 \nRosetta Generic 1160K 287 \nRosetta IndirectBranch 32K 1 \nRosetta JIT 128.0M 1 \nRosetta Return Stack 20K 2 \nRosetta Thread Context 20K 2 \nStack 8176K 1 \nStack Guard 56.0M 1 \nVM_ALLOCATE 4K 1 \nVM_ALLOCATE (reserved) 80K 3 reserved VM address space (unallocated)\n__DATA 2112K 11 \n__DATA_CONST 28K 1 \n__DATA_DIRTY 8K 2 \n__LINKEDIT 1288K 8 \n__TEXT 12.9M 6 \n__TPRO_CONST 4K 1 \nmapped file 15.1M 10 \npage table in kernel 369K 1 \n=========== ======= ======= \nTOTAL 228.9M 341 \nTOTAL, minus reserved VM space 228.8M 341 \n", "legacyInfo" : { "threadTriggered" : { } }, "logWritingSignature" : "c5475baf6d64df516849196fc9e6a86be22be45a", "trialInfo" : { "rollouts" : [ { "rolloutId" : "642da32dea3b2418c750f848", "factorPackIds" : { "VISUAL_INTELLIGENCE_VICTORIA" : "66d8b2f77cd4b62688efd2cf" }, "deploymentId" : 240000004 }, { "rolloutId" : "67fd77fe1f9da9148f70d6ed", "factorPackIds" : { }, "deploymentId" : 240000011 } ], "experiments" : [ ] }, "reportNotes" : [ "RIP register does not match crashing frame (0x0 vs 0x10621FAE0)" ] } Model: Mac16,7, BootROM 11881.140.96, proc 14:10:4 processors, 48 GB, SMC Graphics: Apple M4 Pro, Apple M4 Pro, Built-In Display: Color LCD, 3456 x 2234 Retina, Main, MirrorOff, Online Memory Module: LPDDR5, Micron AirPort: spairport_wireless_card_type_wifi (0x14E4, 0x4388), wl0: Jun 24 2025 04:56:40 version 23.40.31.0.41.51.179 FWID 01-435c4c4d IO80211_driverkit-1485.7 "IO80211_driverkit-1485.7" Jul 15 2025 20:46:41 AirPort: Bluetooth: Version (null), 0 services, 0 devices, 0 incoming serial ports Network Service: Wi-Fi, AirPort, en0 USB Device: USB31Bus USB Device: USB31Bus USB Device: USB31Bus Thunderbolt Bus: MacBook Pro, Apple Inc. Thunderbolt Bus: MacBook Pro, Apple Inc. Thunderbolt Bus: MacBook Pro, Apple Inc.
最新发布
08-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值